提问人:Setu 提问时间:10/6/2022 更新时间:10/7/2022 访问量:775
G++ 未定义的引用,与自定义共享库链接时
g++ undefined reference to while linking with a custom shared library
问:
我正在尝试将我的 C++ 程序与自定义共享库链接。共享库是用 C 语言编写的,但是,我认为这无关紧要。我的图书馆叫做.其完整路径为 。我还添加到了我的所以应该能够找到它。当我跑步时,我得到:libfoo.so
/home/xyz/customlib/libfoo.so
/home/xyz/customlib
LD_LIBRARY_PATH
ld
nm -D libfoo.so
...
00000000000053a1 T myfunc
000000000000505f T foo
0000000000004ca9 T bar
00000000000051c6 T baz
000000000000527f T myfunc2
...
所以我认为我的库是正确编译的。我正在尝试通过运行test.cpp
g++ -L/home/xyz/customlib -Og -g3 -ggdb -fsanitize=address test.cpp -o test -lfoo
但是,我收到以下错误:
/usr/bin/ld: in function sharedlib_test1()
/home/xyz/test.cpp:11: undefined reference to `myfunc()'
/usr/bin/ld: in function sharedlib_test2()
/home/xyz/test.cpp:33: undefined reference to `foo()'
...
我做错了什么?我该如何解决这个问题?请注意,我已经重命名了文件和共享库,因为我无法共享确切的文件和函数名称。
答:
1赞
Setu
10/7/2022
#1
正如帖子中的评论所指出的,事实证明,我在头文件中缺少外部“C”。因此,在我的代码中,我将我的 include 语句包装在一个解决了这个问题的外部“C”中。
TLDR:代码中包含的标头应如下所示:
extern "C" // Import C style functions
{
#include <foo.h>
}
评论
extern "C"
#ifdef __cplusplus
extern "C"
#include
extern "C"