tags:

views:

218

answers:

4

I am writing a (my first) C++ class on top of some code written in C, but I can only get the C++ to compile by declaring the C functions in a extern block. My project uses autotools; is there any way to automate this process so I don't have to maintain two header files?

+3  A: 

Yes create wrapper header files which include your C header files like so...

//Wrapper.h
#ifdef __cplusplus
extern "C"
{

    #include "Actual.h"
}
#else
    #include "Actual.h"
#endif


//Use.cpp
#include "Wrapper.h"

int main()
{
    return 0;
}

//Use.c
#include "Wrapper.h"
/*or #include "Actual.h" */

int main()
{
    return 0;
}
SDX2000
Thanks! Much appreciated.
drkatz
While this certainly works, I think the much higher-rated answer below is better - use the preprocessor in the actual header files to declare the functions `extern "C"`. That way, you can include the header the same way in C and C++, and not have to worry about an extra "wrapper" header.
Chris Lutz
True but what if the actual header cannot be modified? What if it was obtained from a third party/another project whose sources are not being maintained by you?
SDX2000
+14  A: 

Use a extern block inside a #ifdef in C codes header files

Start of header files

#ifdef __cplusplus
extern "C" {
#endif

...and at end of the header files

#ifdef __cplusplus
}
#endif

This way it will work for being included in both C and C++ sources

epatel
+1  A: 

Use the C Preprocessor. Do something like this:

 #ifdef __cplusplus
 extern "C" {
 #endif 
// code goes here

#ifdef __cplusplus
}
#endif
Grant Limberg
+1  A: 

We have a macro in a header file:

#ifdef __cplusplus
    #define _crtn "C"
#else
    #define _crtn
#endif

Then in header files, we can use _crtn:

#include "croutine.h"

extern _crtn void MyFunction( ... );

The only gotcha is to make sure you include the header file containing the prototype of MyFunction inside the file containing the implementation of MyFunction so that it is compiled with "C" linkage.

This is the same as @epatel's answer, but only requires the ugly #ifdef's in one header file.

Graeme Perrow
Little-known fact: you can declare functions as extern "C++", although it's kind of pointless since it's the default when compiling with C++, and C compilers can't compile C++. But it may be useful in the future for the hypothetical C++++ language.
Adam Rosenfield