Is extern “C” only required on the function declaration?

后端 未结 6 1922
执念已碎
执念已碎 2020-12-01 07:48

I wrote a C++ function that I need to call from a C program. To make it callable from C, I specified extern \"C\" on the function declaration.

6条回答
  •  星月不相逢
    2020-12-01 08:10

    The extern "C" around the definition is not required. You can get away with just putting it around the declaration. One note in your example...

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    /* Function declaration */
    void foo(int);
    
    #ifdef __cplusplus
    }
    #endif
    

    Your code is looking for the preprocessor macro "__cplusplus".

    While it's commonly implemented, depending on your compiler, this may or may not be defined. In your example, you also use extern "C" around the declaration, but there you are not checking for the "__cplusplus" macro which is why I suspect it worked once you did that.

    See the comments below — Standard C++ requires the __cplusplus macro to be defined by the preprocessor.

提交回复
热议问题