ld --whole-archive 和 --no-whole-archive學習記錄

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 function main': main.c:(.text+0xa): undefined reference tofunc’
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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章