c++ compiled object files and internal identifiers

76 Views Asked by At

i read here that

A function with internal linkage is only visible inside one translation unit. When the compiler compiles a function with internal linkage, the compiler writes the machine code for that function at some address and puts that address in all calls to that function (which are all in that one translation unit), but strips out all mention of that function in the ".o" file.

i compiled this code

int g_i{};          //extern
static int sg_i{};    //static

static int add(int a, int b) //internal linakge!
{
    return a+b;
}

int main()
{
    static int s_i{}; //static - local
    int a_i{};        //auto - local
    a_i = add(1,2);
    return 0;
}

and compiled using g++ -c and created my main.o file then trying nm -C main.o im getting this result:

0000000000000000 b .bss
0000000000000000 d .data
0000000000000000 p .pdata
0000000000000000 r .rdata$zzz
0000000000000000 t .text
0000000000000000 r .xdata
                 U __main
0000000000000000 t add(int, int)
0000000000000004 b sg_i
0000000000000008 b main::s_i
0000000000000000 B g_i
0000000000000014 T main

can you please explain why those internal identifier are still mentioned in the object file while i heard that linker using these object files will have no idea about their existence?

thanks.

1

There are 1 best solutions below

0
Karen Baghdasaryan On

The linker knows that there is such function. However it also knows that the function that the function with internal linkage is only visible in the translation that translation unit. More simply, it just forbids the call of that function outside the translation unit.

That's why you need those internal identifiers, so that the linker knows that this function belongs only to this translation unit.