gnu 連接器ld的操作 --whole-archive 和 --no-whole-archive
--whole-archive
For each archive mentioned on the command line af-
ter the --whole-archive option, include every ob-
ject file in the archive in the link, rather than
searching the archive for the required object
files. This is normally used to turn an archive
file into a shared library, forcing every object to
be included in the resulting shared library.
--no-whole-archive
Turn off the effect of the --whole-archive option
for archives which appear later on the command
line.
–whole-archive選項解決的是編譯中常遇到的問題。在代碼中定義的符號(如函數名)還未使用到之前,鏈接器並不會把它加入到連接表中:
func.c
************************************************************************/
#include <stdio.h>
void func()
{
printf("in %s\n", __func__);
}
main.c
#include<stdio.h>
extern void func();
int main()
{
func();
printf("in %s\n", __func__);
return 0;
}
編譯
➜ gcc -c func.c
➜ ar -r libfunc.a func.o
➜ gcc -L. -lfunc main.c -o main報錯
/tmp/ccFXELUM.o: In functionmain': main.c:(.text+0xa): undefined reference to
func’
collect2: error: ld returned 1 exit status
解決方式爲使用Wl,–whole-archive告訴連接器將func庫中的符號全部加載到連接表中以備使用:
gcc -Wl,–whole-archive -L. -lfunc -Wl,–no-whole-archive main.c -o main
或者
gcc main.c -L. -lfunc -o main