a.cpp
const unsigned char whatever[123] = { /* ... */ };
啊
extern const unsigned char whatever[123];
b.cpp
#include "a.h"
unsigned char x = whatever[0];
// error: undefined reference to 'whatever'
为什么我得到一个未定义的引用错误? 如果没有const
,错误消失。
如何共享多个翻译单位之间的常量数组?
This is one of the quirks people run into, it's simply a matter that you've defined an a.h header file which declares a const array of 123 chars, and assigned it external linkage. When it is included into the b.cpp file, you're basically promising the compiler it's going to find in some other translation unit.
But, every const
variable has a dark secret - it's trapped inside its defining translation unit because it is implicitly given static linkage. You promised your compiler whatever
will be shared across multiple translation units, but it is actually loyal to just one translation unit and doesn't like to be shared. And, well, you know the rest.
Resolve by explicitly stating extern
in the implementation file.
3.5/3
A name having namespace scope (3.3.5) has internal linkage if it is the name of
...
— an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage;
...
类似的VAR
const int x = 10;
隐式定义为“静态”。
为了让他们非静态的(因此非内部),使用“.c”的文件“的extern修饰符。
尝试使用
extern const unsigned char whatever[123] = { /* ... */ };
常量在默认情况下在C静态的(内部)联动++,在你的.c文件使用的extern const的为好。
这是一个随机的SO线程有更多信息。 或谷歌“++在C链接”。
在C ++中,const为一个编译时间常数,例如,
const int cc = 100;
int a[cc];
我们可以用常量来定义C ++中的阵列,但是可以在不C.既然是常量,其值不能被改变,它不要求将多个文件之间共享它们。 因此说,常量具有内部链接。
为了解决这个问题, a.cpp
应该做的:
#include "a.h"
之前的定义whatever
。
如果在范围没有先前声明然后const unsigned char whatever[123] = {...};
将具有内部链接。 但是,如果ah
对,则定义与先前的声明一致。 头定义whatever
外部链接,并定义的名称相匹配。
正如其他人所说,你也可以把extern
的定义,因此,如果你忘了,不会发生这种错误#include "ah"
。 但它仍然是包括宣布我们正在尝试公开确定任何头的最佳实践。