我在代码中将以下字符串声明为常量。目的是提供一种在编译输出中存储简单元数据的粗略且简单的方法。
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'
block 引用>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/