Andree
Andree

Reputation: 3103

Use C++ shared object from a C program?

I am currently developing a C program depending on a third-party library with a C interface (the header files are written in C). I compile my program by linking all the required .so files, and everything is fine. However, I recently take a peek at the source code of this third-party library. Apparently, it is written in C++ and it does utilize some C++ features (namespaces, OOP, and so on).

Is this even possible? So I can write a library in C++, provide a C interface, generate .so files to hide C++ implementation, and then my library can be used within a C program? Will it cause problems?

Thanks!

Upvotes: 1

Views: 418

Answers (1)

Alok Save
Alok Save

Reputation: 206528

Yes.
The library is written in C++ but it provides an interface which uses C linkage so as to link to your c program.
This is essentially possible because C++ Standard specifically provides provision to specify the Linkage Specification for a C++ program.

For Example:

extern "C" 
{    
    void doSomething(char);    
} 

extern "C" here is the linkage specification it makes the function doSomething() in C++ have 'C' linkage (compiler does not do C++ style1 Name Mangling) this ensures that your C code can link to it.
Since the C++ function definition was already compiled and converted to binary format the client application/library 'C' linker just links to this code using the 'C' name.

1 An example of difference in Name Mangling for C and C++:
C++ supports Function overloading while C does not, So the C++ compiler needs to mangle the name by adding information about the function arguments arguments. A C compiler does not need to use the function arguments to mangle the name since there is no function overloading support.When you use the extern "C" linkage Linkage specification, the C++ compiler does not add function argument information to the name used for linkage.

Upvotes: 5

Related Questions