C++调用C静态库,出现undefined reference to “” 的问题

哥们在搞一个软件C++写的,跑在linux上,中间涉及到需要调用一个内核中的静态库的步骤。
So here comes the trouble。


一开始出现undefined reference to,然而我并不方。这种问题一般都是缺少实现之类的问题。需要添加库,添加头文件路径。添加库路径。So easy!
But!
然而并没有成功,WTF,抓耳挠腮,各种路径查一遍,没错啊,
开始宕机。。。。
But again
感谢蓝灯,感谢google,感谢stackoverflow,

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的库,然后就完成啦!

静态库的"undefined reference to"错误通常是由于链接器无法找到所需的函数或符号的实现引起的。根据引用\[1\]和引用\[3\]的内容,这种错误可能有以下几个原因: 1. 检查.pro文件中是否正确引用了需要调用的库,并且确保库文件存在于正确的位置。 2. 检查头文件是否使用了extern "C"修饰,以确保C++代码正确调用C库中的函数。 3. 确保QT中的编译器位数与编译C库时使用的编译器位数一致,这是一个容易被忽视的问题。 根据引用\[2\]的内容,还有可能是由于编译目标文件扩展名的更改导致的问题。如果你将C++项目的.cpp文件更改为.c文件,但没有将编译器从g++改为gcc,那么生成的目标文件可能仍然包含C++风格的函数名,而与C库中的函数名不一致,从而导致"undefined reference to"错误。 综上所述,解决这个问题的方法包括检查.pro文件中的库引用、修饰头文件、确保编译器位数一致以及正确更改文件扩展名和编译器类型。 #### 引用[.reference_title] - *1* [QT调用C动态/静态库出现undefined reference to xxx和xxx@4](https://blog.csdn.net/AFunnyBoy/article/details/124480245)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [linux 链接 静态库 undefined reference to](https://blog.csdn.net/doubleface999/article/details/55798714)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值