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
2009-02-08 21:48:26
Thanks! Much appreciated.
drkatz
2009-02-08 21:50:08
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
2009-02-09 18:14:31
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
2009-02-09 18:17:03
+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
2009-02-08 21:48:48
+1
A:
Use the C Preprocessor. Do something like this:
#ifdef __cplusplus
extern "C" {
#endif
// code goes here
#ifdef __cplusplus
}
#endif
Grant Limberg
2009-02-08 21:49:29
+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
2009-02-09 17:54:48
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
2009-02-09 18:11:09