How does linkage and name mangling work?

前端 未结 2 1222
温柔的废话
温柔的废话 2021-01-29 00:25

Lets take this code sample

//header
struct A { };
struct B { };
struct C { };
extern C c;

//code
A myfunc(B&b){ A a; return a; }
void myfunc(B&b, C&         


        
相关标签:
2条回答
  • 2021-01-29 01:10

    http://en.wikipedia.org/wiki/Name_mangling

    0 讨论(0)
  • 2021-01-29 01:22

    We first need to understand where compilation ends and linking begins. Compilation involves taking a compilation unit (a C or C++ source file) and turning it into an object file. Simplistically, this involves generating snippets of machine code for each function as well as a symbol table for all functions and static (global) variables. Placeholders are used for any symbols needed by the compilation unit that are external to the said compilation unit.

    The linker is then responsible for loading all the object files and resolve all the place-holder symbols with real addresses (or offsets for machine independent code). This is placed into various sections that can be read by the operating system's dynamic loader when loading an executable.

    So for the specifics. In order to avoid errors during linking, the compiler requires you to declare all external symbols that will be used by the current compilation unit. For global variables one must use the extern keyword, for functions this is optional.

    All functions and global variables defined in a function have external linkage (ie can be referenced by other compilation units) unless one declares that with the static keyword (or the unnamed namespace in C++). In C++, the vtable will also have a symbol needed for linkage.

    Now in C++, since functions can be overloaded, the parameters also form part of the function name. Since machine-code is just addresses and registers, extra information needs to be added to the function name in the symbols table. This extra parameter information comes in the form of a mangled name and ensures that the linker links to the correct version of an overloaded function.

    If you really are interested in the gory details take a look at the ELF file format (PDF) used extensively on Linux. Windows has a different format but the principles can be expected to be the same. Name mangling on the Itanuim (and ARM) platforms can be found here.

    0 讨论(0)
提交回复
热议问题