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

前端 未结 10 1422
失恋的感觉
失恋的感觉 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:37

    Short answer is that you can use extern C to tell the compiler not to use name-mangling. This means you can link together bits of C and C++ code in the same project.

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

    The language permits:

    extern "C" {
      #include "foo.h"
    }
    

    What if foo.h contains something which requires C++ linkage?

        void f_plain(const char *);
        extern "C++" void f_fancy(const std::string &);
    

    That's how you keep the linker happy.

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

    I'm not sure why you would need to do it, but according to this article from Sun, you can use extern "C++" inside a block of extern "C" to specify certain functions in a group of "C" functions have the native C++ linkage.

    extern "C" {
        void f();             // C linkage
        extern "C++" {
            void g();         // C++ linkage
            extern "C" void h(); // C linkage
            void g2();        // C++ linkage
        }
        extern "C++" void k();// C++ linkage
        void m();             // C linkage
    }
    
    0 讨论(0)
  • 2020-12-12 18:44

    C and C++ use different name mangling rules. Essentially, extern "C" tells the C++ compiler to name the function as C would name it.

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