Why would you use 'extern “C++”'?

前端 未结 10 1421
失恋的感觉
失恋的感觉 2020-12-12 17:37

In this article the keyword extern can be followed by \"C\" or \"C++\". Why would you use \'extern \"C++\"\'? Is it practical?

相关标签:
10条回答
  • 2020-12-12 18:19

    Two guesses:

    • If you are in a extern "C" block, you can get C++ language linkage again by specifying a nested extern "C++".
    • It reserves C++ linkage, because it's the document defining C++. Who is in a better position for defining C++ language linkage than it itself. It also provides for completeness. Same deal as with signed/unsigned.

    Read this answer that explains extern "LanguageName" (i.e GCC has extern "Java") aswell.

    0 讨论(0)
  • Extern "C" is answered by many. The use case for extern "C++" is when calling C++ library function in a C function. The sub-use case, that is relevant, is when linking a C++ library with a C source code with main function. Check this wiki page for more details:

    0 讨论(0)
  • 2020-12-12 18:22

    This specify which link convention to use. Most languages know how to link with a "C" style function.

    You need this in two cases :

    • A C - or other languages for that matter- program calling a function written in C++
    • A C++ program calling a function written in C

    Example :

    // declared in function.h
    void f1(void);
    

    Your C code - actually other languages are able to link with C function - will not be able to link to it because the name in the object table will use C++ convention.

    If you write

    extern "C" void f1(void);
    

    Now the linking works because it uses C convention.

    0 讨论(0)
  • 2020-12-12 18:25

    The #1 reason I use extern "C" is to avoid C++'s name mangling rules. This is very important if you are working in a .Net language and want to PInvoke into a particular native function. The only way to do this is with name mangling disabled.

    0 讨论(0)
  • 2020-12-12 18:27

    There is no real reason to use extern "C++". It merely make explicit the linkage that is the implicit default. If you have a class where some members have extern "C" linkage, you may wish the explicit state that the others are extern "C++".

    Note that the C++ Standard defines syntactically extern "anystring". It only give formal meanings to extern "C" and extern "C++". A compiler vendor is free to define extern "Pascal" or even extern "COM+" if they like.

    0 讨论(0)
  • 2020-12-12 18:35

    extern "C" is used to say that a C++ function should have C linkage. What this means is implementation dependant, but normally it turns off C++ name-mangling (and so overloading and strict type checking). You use it when you have a C++ function you want to be called from C code:

    extern "C" void Foo();   // can be called easily from C
    

    As for extern "C++", I've never seen it in real code, though the C++ Standard allows it. I guess it is a no-op.

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