1

我需要在我的 C 代码的 100 行中使用常量字符串“ my_string”。
而且我对最终二进制大小有限制。
那么我应该去哪一个呢?
(我认为const char*更好,因为内存只分配给字符串一次。我是对的......?)

编译器:gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)
编译器选项: -fPIC -Wall -g -O2 -pthread -O2 -g

4

3 回答 3

1

这不是一个真正的答案,但......

我认为你根本不应该担心这个。编译器比我们聪明得多,并且会做最好的事情。您将浪费大量时间尝试优化字符串文字。

只需以对您有意义的方式进行编码。

但是,值得注意的是,如果您尝试优化大小,您可能希望使用 -Os 选项而不是 -O2

-Os 优化大小。-Os 启用所有 -O2 优化,除了那些经常增加代码大小的优化:

-falign-functions -falign-jumps -falign-labels -falign-loops -fprefetch-loop-arrays -freorder-blocks-algorithm=stc 它还启用 -finline-functions,导致编译器调整代码大小而不是执行速度,并执行旨在减少代码大小的进一步优化。

GCC 优化选项

于 2022-02-17T14:18:52.310 回答
0

With the right compiler optimisation settings you won't see any difference in the amount of memory used.

One point that is consistently missed though is that the use of const variables rather than #defines greatly improves the ease of locating coding errors related to them.

In fact the compiler itself will aid you in preventing the introduction of bugs, as it will also perform type checking during compilation on the use of a const variables, whereas they invariably don't on #define.

That is not to say that there isn't a place for #define just that they shouldn't always be your first port of call.

于 2022-02-17T15:17:32.100 回答
-1

如果您使用#define CONST_STR "my_string"它,就好像您在"my_string"任何地方都使用了“新鲜副本”。你的编译器可能会合并这些副本——现在许多编译器理所当然地这样做——或者它可能不会。还有一个问题是你是否会在多个翻译单元中合并副本——现代链接器显然可以做到这一点,但我不知道你的。

如果您使用const char *CONST_STR = "my_string";,则保证您只有一份"my_string". 您可以通过说 . 在另一个翻译单元(即另一个源文件)中访问它extern const char *CONST_STR;

最后,如果您使用,则const char CONST_STR[] = "my_string";可以保证只有一个字符串副本,并且您将通过不分配额外的指针来节省更多字节。您可以通过说 . 在另一个翻译单元(即在另一个源文件中)访问它extern const char CONST_STR[];

底线:我会说绝对不要使用#define. 它可能会浪费大量内存,而且这些天#define往往被弃用,而倾向于使用 const 变量。

于 2022-02-17T14:02:45.210 回答