C++调用C静态库,出现undefined reference to “” 的问题
哥们在搞一个软件C++写的,跑在linux上,中间涉及到需要调用一个内核中的静态库的步骤。So here comes the trouble。一开始出现undefined reference to,然而我并不方。这种问题一般都是缺少实现之类的问题。需要添加库,添加头文件路径。添加库路径。So easy!But!然而并没有成功,WTF,抓耳挠腮,各种路径查一遍,没错啊,开始宕机。。。。
哥们在搞一个软件C++写的,跑在linux上,中间涉及到需要调用一个内核中的静态库的步骤。
So here comes the trouble。
一开始出现undefined reference to,然而我并不方。这种问题一般都是缺少实现之类的问题。需要添加库,添加头文件路径。添加库路径。So easy!
But!
然而并没有成功,WTF,抓耳挠腮,各种路径查一遍,没错啊,
开始宕机。。。。
But again
感谢蓝灯,感谢google,感谢stackoverflow,
But everything works well with other C programs linking this library.
Did you notice that C and C++ compilation create different symbol names on object file level? It’s called ‘name mangling’.
The (C++) linker would show undefined references as demangled symbols in the error message, which might confuse you. If you inspect your test.o file with nm -u you’ll see that the referenced symbol names don’t match with those provided in your library.
If you want to use functions linked in as externals that were compiled using the plain C compiler, you’ll need their function declarations enclosed in an extern “C” {} block which suppresses C++ name mangling for everything declared or defined inside, e.g.:
extern "C"
{
#include <dual/xalloc.h>
#include <dual/xmalloc.h>
}
Even better, you might wrap your function declarations in your header files like this:
#if defined (__cplusplus)
extern "C" {
#endif
/*
* Put plain C function declarations here ...
*/
#if defined (__cplusplus)
}
#endif
在添加头文件的时候需要告诉编译器这个是C的库,然后就完成啦!
更多推荐
所有评论(0)