tags:

views:

206

answers:

4

I know this.

Calling C function from C++:

If my application was in C++ and I had to call functions from a library written in C. Then I would have used

//main.cpp

extern "C" void C_library_function(int x, int y);//prototype
C_library_function(2,4);// directly using it.

This wouldn't mangle the name C_library_function and linker would find the same name in its input *.lib files and problem is solved.

Calling C++ function from C???

But here I'm extending a large application which is written in C and I need to use a library which is written in C++. Name mangling of C++ is causing trouble here. Linker is complaining about the unresolved symbols. Well I cannot use C++ compiler over my C project because thats breaking lot of other stuff. What is the way out?

By the way I'm using MSVC

+2  A: 

export your C++ functions as extern "C" (aka C style symbols), or use the .def file format to define undecorated export symbols for the C++ linker when it creates the C++ library, then the C linker should have no troubles reading it

Necrolis
+6  A: 

You need to create a C API for exposing the functionality of your C++ code. You might find my coding conventions for creating public C APIs useful, especially with regard to creating OOP-style C code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.

Michael Aaron Safyan
thanks!! got it. http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.6
claws
+5  A: 

Assuming the C++ API is C-compatible (no classes, templates, etc.), you can wrap it in extern "C" { ... }, just as you did when going the other way.

If you want to expose objects and other cute C++ stuff, you'll have to write a wrapper API.

Marcelo Cantos
Not quite... the C++ library would need to be recompiled.
Michael Aaron Safyan
Oh no. C++ API is fully object-oriented.
claws
@claws, see my article on making OOP-style C code.. and create a wrapper library using that style with a C interface, but an underlying C++ implementation. Then link to the C interface.
Michael Aaron Safyan
You may want to take a look at wrapper 'tools' like swig, pyboost, ... that do equivalent stuff (yet not towards C...)
xtofl
+2  A: 

You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.

DeadMG