【发布时间】:2012-05-30 12:34:43
【问题描述】:
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,错误就会消失。
如何在多个翻译单元之间共享一组常量?
【问题讨论】:
-
你不应该只在标题中声明它为 const 吗?您在标头中有一个外部变量,在 cpp 中有相同的变量...我会写:
extern const unsigned char whatever[] = {'a','b',/*.etc.*/}仅在我的标头中 -
将
extern也添加到a.cpp中的定义中。 -
a.cpp是否包含#include "a.h"?如果没有,那么你应该添加它。
标签: c++ arrays header linker constants