Search code examples
c++clinkerexternlinkage

extern "C" (C linkage) by default


Question

Do GCC, MSVC, or Clang, or some combination support setting linkage to default to C?

Background

I have a large mixed C/C++ project, and while it's easy and logical to export symbols in the C++ sources with C linkage, those same sources are assuming the stuff in the rest of the project are under C++ linkage.

The current situation requires me to explicitly wrap anything the C sources use that is defined in the C++ sources and everything the C++ sources use from the C sources with extern "C++".

To top things off, I can't put extern "C" around entire source or header files, as the actual C++ stuff will then complain. (Such as from #include <memory> or templates I've defined.)


Solution

  • The standard pattern in a header file is:

    #ifdef __cplusplus
    
    // C++ stuff
    
    extern "C" {
    #endif
    
    // C/C++ stuff
    
    #ifdef __cplusplus
    }
    #endif
    

    I'm not sure you've got any other options. The C/C++ stuff must be declared with C linkage everywhere. The C++-specific stuff must be declared with C++ linkage everywhere.