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

发布了134 篇原创文章 · 获赞 20 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/u011583798/article/details/83051864
LD