我在 C 文件中有一个变量,该变量在刚刚声明和初始化的任何地方都没有使用。 我希望在 map 文件中为该变量分配内存,但目前尚未发生。我想处理特定文件中的所有变量。
最佳答案
您的编译器正在优化未使用的变量。
为了防止这种情况发生(在 GCC 中),您可以应用 used attribute :
int unreferenced_global_variable __attribute__((used)) = 42;
<小时/>
used
This attribute, attached to a variable with the static storage, means that the variable must be emitted even if it appears that the variable is not referenced.
When applied to a static data member of a C++ class template, the attribute also means that the member is instantiated if the class itself is instantiated.
在我看来,更好的解决方案是在链接描述文件中指定这些类型的变量,并在头文件中添加它们的 extern
定义。但这实际上取决于您为什么要这样做,而您没有告诉我们。
关于c - 未使用的变量未在映射文件中分配地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775804/