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

前端 未结 7 2115
南笙
南笙 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:25

    What does all this mean? For example, what linkage does the f2() function have, C or C++ language linkage?

    extern "C" typedef void FUNC();
    FUNC f2;
    // the name f2 has C++ language linkage and the 
    // function's type has C language linkage 
    

    What you're calling the "f2() function" has two aspects to its linkage:

    • the mangling or not of its name in the symbol table (which has C++ language linkage), and
    • the C or C++ calling convention necessary should the function be called (C).

    To call f2() you find its name aka symbol in the object file, which will be a mangled version of "function named f2 taking no arguments". You can verify this trivially by compiling the above code and inspecting the object (e.g. w/ GNU tools nm --demangle).

    But to call the function, the conventions for pre- and post-conditions re register usage, stack setup etc. are those of a C functions. It is legal for C and C++ functions to have different calling conventions, and might be done - for example - to facilitate C++ exception handling.

    Please explain the differences in the object file: a function's name with C language linkage and C++ language linkage.

    • for C linkage, "f2" would be the symbol in the object file resulting from f2()
    • for C++ linkage, some mangled version of "function named f2 taking no arguments" (for GNU, _Z2f2v which demangles to f2())

    a function's type with C language linkage and C++ language linkage.

    As discussed above, this is about the register/stack usage convention for calling the code at the function's address. This meta-information is not necessarily stored in the symbol table information of the object (and certainly isn't part of the symbol name key itself).

    Further, because each function adopts one of the calling conventions, a compiler needs to know the calling convention to use when following a pointer to a function: with that insight, I think the remaining code in the question becomes clear.

    There's an excellent discussion at http://developers.sun.com/solaris/articles/mixing.html - in particular I recommend the section Working with Pointers to Functions.

提交回复
热议问题