What does mean for a name or type to have a certain language linkage?

前端 未结 7 2118
南笙
南笙 2021-02-01 02:14

According to (c) ANSI ISO/IEC 14882:2003, page 127:

Linkage specifications nest. When linkage specifications nest, the innermost one determines the langu

7条回答
  •  余生分开走
    2021-02-01 02:31

    As we all know in C/C++ code translation is composed of two principal phases: compilation and linking. When compiler generates object files it passes information to linker specifying in which object files given function is called or referenced. In C it is just like that, function has a name and matching definition.

    // file1.c
    void foo(void) {}
    

    And after compilation file1.obj stores the code and information about the definition of the foo symbol.

    But when C++ comes in the symbol names become more complicated. A function may be overloaded or be a member of a class. But the linker does not want to know it. To preserve simplicity and re-usability of older linkers it needs a single name whether foo is:

    void foo(void) {}
    void foo(int) {}
    void ClassA::foo(void) {}
    

    But it cannot be called just foo anymore so here comes name mangling. And we may get from the compiler some variations like foo_void, foo_int, foo_void_classa. And finally the linker is happy as all those look to it like simple symbols.

    When we want to call the foo function compiled with the C compiler in C++ code we must tell the compiler that we want foo to be C style foo and not foo_void as C++ compiler might assume. It is done using:

    extern "C" void foo();
    

    Now the compiler knows that foo is compiled using C compiler and will pass information to the linker that this code calls foo. The linker will match it with the foo definition in file1.obj. So it's all I think.

    Some other directives like cdecl or stdcall are Windows specific and tell how parameters in function calls are being passed. Yes, for C and C++ it is cdecl. But Windows API functions use stdcall - Pascal convention (simplicity and historically Microsoft once provided Windows dev environment in Pascal).

提交回复
热议问题