c - 未使用的变量未在映射文件中分配地址

标签 c gcc linker compiler-optimization

我在 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/

相关文章:

c - 如果用户键入更多字符,我如何只读取一个字符而忽略其他字符?

c++ - '从 some_type** 到 const some_type** 的无效转换'

c - 构建 GCC 失败 (/bin/sh gcc-4.9.2/config.sub gmp)

c++ - 标识符节点*未定义(链接器问题)

c++ - 链接器找不到命名空间的函数

c++ - 在单个节点上,我是否应该选择 MPI 而不是其他进程间机制?

c - 没有默认大小写的 Objective-C 枚举 "exhaustive"开关的行为

c - 在 'C' 中的结构元素之间手动插入填充字节

linux - 为什么ldconfig能够找到一个库,但是找不到Rust?

c - 如何在C中包含头文件