针对静态库的 G++ 链接

g++ linking against static library

本文关键字:G++ 链接 静态      更新时间:2023-10-16

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