编译错误:[build]main.cpp:8:对"托盘"的未定义引用
示例代码:common.cpp
const unsigned char pallete[] = {0, 60, 100, 119};
int a = 1;
main.cpp
#include <iostream>
extern const unsigned char pallete[];
extern int a;
int main() {
std::cout << a << std::endl;
std::cout << pallete[0] << std::endl;
return 0;
}
您必须在common.cpp
中声明托盘extern
。现在main.cpp
知道它应该在单独的文件中"寻找"托盘,但common.cpp
将其视为本地,因为它是const
,正如这里所说https://en.cppreference.com/w/cpp/language/cv#Notes
票据
在未声明为外部的非本地非易失性非模板(自C++14以来(非内联(自C++17以来(变量的声明中使用的const限定符为其提供了内部链接。这与C不同,在C中const文件作用域变量具有外部链接。
extern const unsigned char pallete[] = {0, 60, 100, 119};
int a = 1;
您的编译器很可能会执行我的警告:Warnung: variable 'pallete' is not needed and will not be emitted
如果您将extern
语句也添加到common.cpp
中,它应该可以工作。
如果您声明某个extern
,则应该始终在某个标头中进行声明,该标头由所有想要使用该变量的人包含。
可以添加外部:
externconst unsigned char pallete[]={0,60,100,119};
翻译单元将其视为外部,尽管它是常量。。。