Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

G++ name mangling of global const variables

Can someone help me understanding the gcc name mangling conventions?

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:

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

Is this intended behaviour? For me it looks inconsistent.

like image 378
C-Hoernsche Avatar asked Jun 12 '13 11:06

C-Hoernsche


People also ask

What is the purpose of name mangling in C++?

Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. Name mangling is commonly used to facilitate the overloading feature and visibility within different scopes.

Is Const global variable?

You just use const at global scope: const aGlobalConstant = 42; That creates a global constant. It is not a property of the global object (because const , let , and class don't create properties on the global object), but it is a global constant accessible to all code running within that global environment.

What is name mangling and why do programming languages like C++ use name mangling?

In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.


1 Answers

Mangling is mostly used to distinguish linker symbols that would otherwise reasonably clash.

Since x is implicitly static, multiple translation units can legally have different variables all called x, so the symbol is mangled to avoid collisions.

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).

The other use is for functions, to distinguish overloads with the same name but different argument lists. That clearly doesn't apply here.

like image 168
Useless Avatar answered Oct 01 '22 01:10

Useless