gpt4 book ai didi

编译器优化不编译常量?

转载 作者:行者123 更新时间:2023-12-02 22:30:06 26 4
gpt4 key购买 nike

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

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 标志将每个定义放入目标文件中它自己的部分。这允许链接器轻松确定未引用数据项或函数,并将其从最终二进制文件中省略。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com