Question

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?

Was it helpful?

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.

OTHER TIPS

Another way of doing this is as follows

// intro
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif

// content
EXTERN_C int isPrime(int64_t p);
// many other functions declared with EXTERN_C

Normally the "intro" part is placed in some common header file for everyone to use.

The advantage of this format is that each declaration is immediately seen as extern "C". A reader doesn't have to search around for possible extern "C" {

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

That way, you can extend the int isPrime(int64_t p); part arbitrarily without repeating it in your #ifdef and #else cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top