0

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!

Andree
  • 3,033
  • 6
  • 36
  • 56
  • Try typing in "C++ library C interface" into the search bar on the top right of this site. – Chris Eberle Nov 15 '11 at 05:35
  • Ah yes, somehow I didn't find that post before. Anyone can mark this as a duplicate to: http://stackoverflow.com/questions/4978330/c-library-with-c-interface – Andree Nov 15 '11 at 05:42

1 Answers1

4

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533