我正在尝试查找 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/