我想知道如何在 C++ 中使用我创建的静态库,首先是库:
// header: foo.h
int foo(int a);
.
// code: foo.cpp
#include foo.h
int foo(int a)
{
return a+1;
}
然后我先编译库:
- g++ foo.cpp
- ar rc libfoo.a foo.o
现在我想在一些文件中使用这些库,例如:
// prog.cpp
#include "foo.h"
int main()
{
int i = foo(2);
return i;
}
我现在必须如何编译这些? 我做了:
g++ -L. -lfoo prog.cpp
但是得到一个错误,因为找不到函数 foo
最佳答案
你想要:
g++ -L. prog.cpp -lfoo
不幸的是,ld 链接器对库的顺序很敏感。当试图满足 prog.cpp 中的 undefined symbol 时,它只会查看在命令行上出现在 prog.cpp 之后的库。
您也可以只在命令行上指定库(必要时使用路径),而忘记 -L 标志:
g++ prog.cpp libfoo.a
关于c++ - 如何将静态库 (.a) 添加到 C++ 程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5870026/