Question

I'm trying to compile some code that use a function implemented in a static library named staticlib.a. I also have the header named staticlib.h which contain the declaration of that function. My main, that is contained in the main.c file wich include staticlib.h, only calls that function and no else. So I compile with gcc main.c staticlib.a and everything work fine. I need some feature of c++ but if I properly change main.c in main.cpp and compile same way gcc main.cpp staticlib.a an undefined reference to my function occured. How can I make this works? And why this problem occurred? I cannot really find an explanation in any site i visited... Thank you for all trhe answers.

Était-ce utile?

La solution

you have to define the function in the library as a 'C' function, not a C++ function - do this in your main.cpp

extern "C"
{
#include "staticlib.h"
}

Autres conseils

C and C++ compile differently, C++ uses name mangling (embedding C++ type information in the object file). To stop this behaviour so that you can link to C code from C++, you can use the extern C syntax in C++ when including the C header file.

Please see here http://www.cplusplus.com/forum/general/1143/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top