编译器优化不编译常量?

标签 c gcc arm ld

我在代码中将以下字符串声明为常量。目的是提供一种在编译输出中存储简单元数据的粗略且简单的方法。

const char myString1[] ="abc123\0";
const char myString2[] = {'a','b','c','1','2','3','\0'};

当我使用十六进制编辑器检查输出时,我看到其他字符串常量,但没有出现“abc123”。这让我相信启用的优化导致这些行无法编译,因为它们从未在程序中被引用。

代码中是否有一种方法可以强制其编译,或者是否有其他方法(在代码中)将此元数据放入二进制文件中?我不想对二进制后编译进行任何操作,目标是使其尽可能简单。

编译器标志

-O2 -g -Wall -c -fmessage-length=0 -fno-builtin -ffunction-sections -mcpu=cortex-m3 -mthumb

最佳答案

我认为您正在寻找 used属性:

`used'

This attribute, attached to a variable, 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 will be instantiated if the class itself is instantiated.

应用它就像

__attribute__((used))
const char myString1[] ="abc123\0";
__attribute__((used))
const char myString2[] = {'a','b','c','1','2','3','\0'};

鉴于您发布的编译器标志,几乎可以肯定它是链接器。 -ffunction-sections flag 将每个定义放入目标文件中自己的部分。这使得链接器可以轻松确定数据项或函数未被引用,并将其从最终的二进制文件中省略。

关于编译器优化不编译常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12414012/

相关文章:

无法执行 netcat

更改指向第一个指针的另一个指针的值

c - ARM故意膨胀编译代码?

azure - 如何通过 ARM 模板在 StorageAccount 中设置选定的网络

我真的可以做一个像宏这样的功能吗

c - fwrite后目标文件为空c语言

c - 如何从一个非常简单的示例使用 Makefile

macos - 在安装了 Developer Tools 的情况下为 OSX 获取 GCC

c++11 参数包错误行为与 Apple LLVM 7.0.0 但适用于 GCC-5.1

c - C中的可变长度数组,它们是如何编译的