Mixing C/C++ code

From time to time you may need to borrow library written in C and compile them with your C++ program. You may notice that simply including the C headers and compiling them will result in error, citing improper references to the function. The reason is due to C++ name mangling mechanism which tries to generate unique name for each function definition. This is especially useful in C++ where there can be multiple functions with same name but different parameters. On the other hand, C does not permit function with same name.

So in order to include C library in C++, use:

extern "C" {
#include "header.h" // C library code here...

By using extern you are telling the compiler not perform name mangling on the specified functions in the library. Then you can just call the function as usual.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.