c - 在 c 中,控制编译器如何将相同字符串合并到可执行文件中的规则是什么

标签 c compiler-construction

我正在尝试查找 C 和 C++ 编译器将字符串放入可执行文件的数据部分的规则,但不知道去哪里查找。我想知道规范是否保证以下所有地址在 c/c++ 中相同:

char * test1 = "hello";
const char * test2 = "hello";
static char * test3 = "hello";
static const char * test4 = "hello";
extern const char * test5; // Defined in another compilation unit as "hello"
extern const char * test6; // Defined in another shared object as "hello"

在windows上测试,都一样。但是我不知道它们是否适用于所有操作系统。

最佳答案

我想知道规范是否保证以下所有地址在 c/c++ 中都相同

字符串字面值可以是同一个对象,但不是必须的。

C++ 说:

(C++11, 2.14.5p12) "Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined."

C 说:

(C11, 6.5.2.5p7) "String literals, and compound literals with const-qualified types, need not designate distinct objects.101) This allows implementations to share storage for string literals and constant compound literals with the same or overlapping representations."

C99 基本原理说:

"This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and to perform certain optimizations"

关于c - 在 c 中,控制编译器如何将相同字符串合并到可执行文件中的规则是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370036/

相关文章:

c - 为什么既要使用匿名枚举又要为常量定义宏?

linux - 裸机交叉编译器输入

为多个 C 文件创建 makefile

c - 如何在 C 语言中预取指针,针对 AMD Opteron 6168?

c++ - 我应该将我的程序从 C 更新到现代 C 还是 C++?

c - 使用循环平铺从矩阵中提取子矩阵

c++ - 在源文件中指定包含前缀与在编译器的搜索路径参数中指定包含前缀有何优缺点?

pdf - 为什么 LaTeX/pdflatex 编译器如此 'funky' 与 c++ 相比,需要多次编译和虚假错误消息等?

c - printf 忽略单个反斜杠 '\'

c - MPI——在多台计算机上执行程序