针对静态库的 G++ 链接
g++ linking against static library
my main.cpp
:
#include <iostream>
int foo(int arg);
using namespace std;
int main()
{
int x = foo(22);
cout << x;
return 0;
}
编译命令行(Ubuntu 13.10):
g++-4.8 -L. -lfoo main.cpp -o main_app
libfoo.a
包含int foo(int)
但我总是收到相同的编译器错误:
/tmp/cciAyTSP.o: In function `main':
main.cpp:(.text+0x19): undefined reference to `foo(int)'
collect2: error: ld returned 1 exit status
当然,如果没有可重现的情况,就不可能确定,但一个常见的错误是,如果函数foo
是用 C 编写的,那么你需要把
extern "C" { int foo(int); }
在C++程序的.h
文件中,让它知道该函数不是用C++编写的。
要编写对 C 和 C++都有益的跨语言头文件,常见的方法是
#ifdef __cplusplus
extern "C" {
#endif
... C declarations ...
#ifdef __cplusplus
}
#endif
除了 6502 的答案和 Xephon 的建议之外,还要注意选项的顺序很重要。而不是:
g++-4.8 -L. -lfoo main.cpp -o main_app
你应该写:
g++-4.8 main.cpp -o main_app -L. -lfoo
这是因为ld
是单传递链接器。它不会重新访问图书馆libfoo
使用它中的符号进行main_app.o
。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- CMake-按正确顺序将项目与C运行时对象文件链接
- 从链接列表c++中删除一个项目
- 有根的二进制搜索树.保留与其父级的链接
- 读取文件的最后一行并输入到链接列表时出错
- 静态数据成员的问题-修复链接错误会导致编译器错误
- node-gyp 在 macOS 上未正确链接库
- 基于boost的程序的静态链接——zlib问题
- 无法链接 CMake 中的本地库
- 内联函数中具有内部链接的全局变量
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 使用gcc从静态链接的文件中查找可选符号
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 下面是我为检测链接列表中的循环而制作的代码
- 有了gcc,是否可以链接库,但前提是它存在
- 使用C链接在函数内部创建C++模板
- Visual Studio mkl_link_tool.exe链接错误
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 有人能帮我处理这个链接列表吗?C++