Using C++ library in C code Using C++ library in C code c c

Using C++ library in C code


Yes, this is certainly possible. You will need to write an interface layer in C++ that declares functions with extern "C":

extern "C" int foo(char *bar){    return realFoo(std::string(bar));}

Then, you will call foo() from your C module, which will pass the call on to the realFoo() function which is implemented in C++.

If you need to expose a full C++ class with data members and methods, then you may need to do more work than this simple function example.


C++ FAQ Lite: "How to mix C and C++ code".

Some gotchas are described in answers to these questions:

  • [32.8] How can I pass an object of a C++ class to/from a C function?
  • [32.9] Can my C function directly access data in an object of a C++ class?


Main gotcha: exceptions can not be caught in C. If there is the possibility of an exception rising in the C++ code, either write your C code or your C++ wrappers very carefully. Conversely, exception like mechanisms (i.e., longjump) in the C code (as found in various scripting languages) are not required to invoke destructors for C++ objects on the stack.