即使不使用extern,在头文件中定义的全局变量,也可以被引用了该头文件的外部源文件使用。那extern存在的意义是什么?它要解决什么问题?
test.h
#ifndef __TEST1_H
#define __TEST1_H
int kVar = 1; // 测试不使用extern
// extern int kVar;
void test1();
void test2();
#endif
test1.cpp
#include <iostream>
#include "test.h"
using namespace std;
//int kVar = 1;
void test1() {
kVar += 10;
cout << "in test1: " << kVar << endl;
}
test2.cpp
#include <iostream>
#include "test.h"
using namespace std;
void test2(){
kVar += 20;
cout << "in test2 : " << kVar << endl;
}
main.cpp
#include "test.h"
int main() {
test1();
test2();
return 0;
}
编译
编译不报错。
$ g++ -c main.cpp test1.cpp test2.cpp
链接
链接报错
$ g++ -o main main.o test1.o test2.o
test1.o:test1.cpp:(.data+0x0): multiple definition of `kVar'; main.o:main.cpp:(.data+0x0): first defined here
test2.o:test2.cpp:(.data+0x0): multiple definition of `kVar'; main.o:main.cpp:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
test1.cpp 和 test2.cpp 中都引用了test.h,test1.o和test2.o中都有 kVar 的符号定义,所以在链接时才会报重复定义的错误。解决此问题要在test.h中声明 kVar,且仅在一个.cpp文件中定义kVar,确保kVar仅被定义一次。
一开始提到的困惑是 “即使不使用extern,在头文件中定义的全局变量,也可以被引用了该头文件的外部源文件使用”。对于全局变量仅被单个.cpp文件使用的情况,可以不使用extern。而extern要解决的问题是,多个.cpp文件使用同一个全局变量时,使用extern可以使该全局变量在头文件中仅声明而不定义。再让唯一一个.cpp文件定义该变量,实现仅定义一次全局变量。
只在头文件中声明,不在头文件中定义。所有定义都交给源文件做。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。