Search code examples
c++cname-manglingextern-c

How Do I layout Function Prototypes mixing C with C++


I have a header that I want to include from .c and .cpp files.

so I know about name mangling and extern "C" so...

#ifdef __cplusplus
extern "C"
{
    int isPrime(int64_t p);
}
#endif

but when I include this in the .c file it doesn't see the function because of the #ifdef __cplusplus

so then I end up making 2 copies:

 #ifdef __cplusplus
    extern "C"
    {
        int isPrime(int64_t p);
    }
 #else
     int isPrime(int64_t p);
 #endif

is there a better way to do this... I thought about making another header called prototypes.h and including that in those 2 places... but is there something simple I am missing?


Solution

  • Yes, there is a better way. People are usually doing this :

    #ifdef __cplusplus
    extern "C"
    {
    #endif
        int isPrime(int64_t p);
    #ifdef __cplusplus
    }
    #endif
    

    If you want to do something different in c and c++ (like for example this) then you can use the 2nd syntax in your question.