tags:

views:

155

answers:

4

I'm using a library which has both a C interface and a C++ interface in my C++ program. The C++ one is a bit immature and I must stick with the C one. I was wondering, in more general terms, is there anything specific to keep in mind when mixing C-style binary object files with a C++ project?

+1  A: 

Calling C functions from C++ programs is pretty common. There is only one thing to keep in mind - use a C++ linker :) Also keep in mind that C functions cannot use exceptions, so you have to check their return values.

Edit: others have pointed out that C function declarations should be wrapped in extern "C" {...}. Usually this is already done in library header files.

Messa
+2  A: 

C functions have to be declared as extern "C", if your C header files don't do this automatically, you can do it like this for the whole header:

extern "C"
{
    #include "c-library.h"
}

Otherwise, as long as you use a C++ linker for everything all will be fine :).

KillianDS
The runtime linker is not C- or C++-specific. The C functions will need to be declared `extern "C"` regardless.
Roger Pate
Indeed, my bad, I'll edit the answer.
KillianDS
+5  A: 

For C functions to be called from C++, they have to be declared as extern "C". Usually something like this is used in headers:

#if defined(__cplusplus)
extern "C" {
#endif

void f();
void g();

#if defined(__cplusplus)
}
#endif
sbi
+1  A: 
Nikolai N Fetissov