我在头文件中有以下静态数组:
static MyStruct_t MyStructArray[] = {
......
......
......
}
Run Code Online (Sandbox Code Playgroud)
但是gcc发出警告:
warning: `MyStructArray' defined but not used
Run Code Online (Sandbox Code Playgroud)
处理这种情况的正确方法是什么?
UPD:
将数组定义为const:
const MyStruct_t MyStructArray[] = {
......
Run Code Online (Sandbox Code Playgroud)
解决了这个问题.那么标题中extern或const的首选方式是什么?
因为你已经在头文件中声明了数组静态,所以每个编译单元(即预处理的.cpp文件)都会得到它自己的数组副本 - 几乎肯定不是你想要的,并且肯定是你获得了"定义但是没用过"错误.
相反,您可能希望在头文件中使用它:
extern MyStruct_t *MyStructArray;
Run Code Online (Sandbox Code Playgroud)
...然后正好在1.cpp文件中:
MyStruct_t MyStructArray[] = { ...};
Run Code Online (Sandbox Code Playgroud)