c/c++在头件中定义变量引起的重定义

因为打算定义一个全局使用的变量,所以想着把所有的要实现的东西放在一个头文件中。如下:

1
2
3
4
5
6
7
#ifndef Data_H
#define Data_H
const char* testArray =
{
"testArray",
};
#endif

本想着有:

1
2
3
#ifndef
#define
#endif

的嵌套,这样也应该只会执行一次,可是Link的时候无情得抛出了duplicate declare的错误。很是纳闷。想着不是自己想的那样。于是改成了:

1
2
3
4
5
6
7
#ifndef Data_H
#define Data_H
const static char* testArray =
{
"testArray",
};
#endif

把testArray改成static .成功的Link了。可是在使用的时候发现实际上这个testArray并不是同一个数组,如下:

1
2
3
4
5
6
//object1.h
class Object1
{
public:
Object1();
};

1
2
3
4
5
//object1.cpp
Object1::Object1()
{
cout<<&testArray<<endl;
}
1
2
3
4
5
6
7
//object2.h
class Object2
: public Object1
{
public:
Object2();
};
1
2
3
4
5
//object2.cpp
Object2::Object2()
{
cout<<&testArray<<endl;
}
1
2
3
4
5
//main.cpp
void main()
{

auto obj = new Object2();
}

会得到两个不一样的指像testArray的地址。
默默得再也不敢在头文件中定义变量了。改成了:

1
2
3
4
5
//data.h
#ifndef Data_H
#define Data_H
extern const char*testArray[];
#endif

1
2
//data.cpp
const char *testArray[] = {"testArray"};