Using C library in C++ project

Hi All,

I've a library written in C, I tried to use it inside my C++ project but I got many error messages said "Undefined reference to".

How I can use C library in C++ project?

P.S.
I successfully used that library in C project but as soon as I rename the extension of the file from C to CPP I got a huge of errors!
Are the headers prepared to be used by C++?
1
2
3
4
5
6
7
8
9
#ifdef __cplusplus
extern "C"{
#endif

//C declarations

#ifdef __cplusplus
}
#endif 

An alternative is to wrap the includes with the extern "C":
1
2
3
extern "C"{
#include "Cheader.h"
}


You need to do this because if the C++ compiler doesn't know it's looking at C declarations it'll try to mangle the function names, but the C function definitions won't be mangled, so when the time comes to link everything, the linker won't find the definitions.
extern "C" tells the compiler that the declarations inside shouldn't be mangled.
Last edited on
Are the headers prepared to be used by C++?

Actually No, I don't know what the benefit of extern "C" until now.
Thanks a lot, this solution fixed the errors.
Topic archived. No new replies allowed.