简体   繁体   English

G ++名称修改全局const变量

[英]G++ name mangling of global const variables

Can someone help me understanding the gcc name mangling conventions? 有人可以帮我理解gcc名称修改约定吗?

Consider the following test code 请考虑以下测试代码

#include <stdio.h>

const int x = 42;
int y = 42;

int main( int argc, const char* argv[] )
{
        return 0;
}

When running nm I get the following (surprising?) result: 运行nm我得到以下(令人惊讶的?)结果:

0000000000000000 T main
0000000000000000 D y
0000000000000000 r _ZL1x

This shows that the compiler only mangles global variables placed in the read only section. 这表明编译器只会破坏放在只读部分中的全局变量。 I would expect the compiler either to mangle ALL or NO global variables 我希望编译器能够修改ALL或NO全局变量

Is this intended behaviour? 这是预期的行为吗? For me it looks inconsistent. 对我来说,它看起来不一致。

Mangling is mostly used to distinguish linker symbols that would otherwise reasonably clash. Mangling主要用于区分链接符号,否则这些符号会合理地发生冲突。

Since x is implicitly static, multiple translation units can legally have different variables all called x , so the symbol is mangled to avoid collisions. 由于x是隐式静态的,因此多个转换单元在法律上可以使用所有称为x不同变量,因此符号会被损坏以避免冲突。

Since y is not static, there can be only one global variable called y in the program, so there's no need to avoid collisions (they should either be flagged as ODR violations or de-duplicated by the linker). 由于y 不是静态的,因此程序中只能有一个名为y全局变量,因此不需要避免冲突(它们应该被标记为ODR违规或链接器重复删除)。

The other use is for functions, to distinguish overloads with the same name but different argument lists. 另一个用途是用于函数,以区分具有相同名称但不同参数列表的重载。 That clearly doesn't apply here. 这显然不适用于此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM