I often hear people say that C++ programmers should expose their library’s/product’s public API as a C API.
What does that mean and what are the advantages of that?
It does mean that the part of your library that is exposed as an interface only uses the C “part” of the language, so you’re not exporting classes or similar, only functions, PODs and structs containing PODs. Plus, you have to disable the C++ name mangling, usually achieved by marking functions as extern "C"
. A typical example would be:
extern "C" void foo(int bar);
The big advantage of exposing your libraries in this fashion is that pretty much every programming language out there has a mechanism to directly interface with a C library, but only very few can also interface directly with a C++ library. So in that sense, you go for the lowest common denominator to make it easy for other people to use your library.
However keep in mind that this is really only a useful strategy if you are producing a library for other people to consume. If you are building a piece of C++-only software and the libraries only need to interface with each other, you are (IMHO) better off exposing proper C++ APIs so you can make use of the full power of the language.
6
In addition to Timo’s answer – there is no standarised C++ ABI for some platforms (for example Windows – some like Linux of Mac OS X widely adopted) so it is not only matter of missing feature but impossibility of implementing such feature.
For example IIRC MSVC have different ABI in each version and it might change depending whether it is debug or release build – and it is not published so 3rd party compilers are usually not compatible (I read some information that some version of icc is compatible with MSVC 2005 but it might be information disclosed under NDA – not necessary available to creators of say Python) and use their own ABI. So in practice language environment would limit not only the compiler version but also flags.
Finally C++ have much more compile-time features. For example generics usually don’t exists in the dynamically typed languages etc.
1