转自gcc和ld 中的参数 --whole-archive 和 --no-whole-archive
首先 --whole-archive 和 --no-whole-archive 是ld专有的命令行参数,gcc 并不认识,要通gcc传递到 ld,需要在他们前面加-Wl,字串。
--whole-archive 可以把 在其后面出现的静态库包含的函数和变量输出到动态库,--no-whole-archive 则关掉这个特性。
比如你要把 liba.a libb.a libc.a 输出到 libabc.dll(或libabc.so)时应该这么写:
libabc.dll:liba.c libb.a libc.a
gcc -shared -o $@ -L. -Wl,--whole-archive -la -lb -lc -Wl,--no-whole-archive
在--whole-archive作用下的库里不能有函数同名。
下面有一个包含Makefile 和c的完整例子:
#dllMake
all:ap lib
exe=main.exe
dll=libabc.dll
lib:$(dll)
ap:$(exe)
src=main
sa = a b c
$(exe):$(src:%=%.c) $(dll)
gcc $< -labc -L. -o $@
$(dll):$(sa:%=lib%.a)
gcc -shared -o $@ -L. -Wl,--whole-archive $(sa:%=-l%) -Wl,--no-whole-archive
lib%.a:%.o
ar rcs $@ $<
%.o:%.c
gcc $< -g -c -o $@
clean:
# -rm $(sa:%=%.o)
# -rm $(src:%=%.o)
-rm $(sa:%=lib%.a)
-rm $(dll)
-rm $(exe)
//a.c
#include <stdio.h>
int func_a(int arg1)
{
printf("a %d\n" , arg1);
return 25*arg1;
}
int samefun()
{
printf("%s in %s\n", __FUNCTION__ , __FILE__ ) ;
}
// b.c
#include <stdio.h>
int func_b(int arg1)
{
return 2*arg1;
}
// c.c
#include <stdio.h>
int func_c(int arg1)
{
return 3*arg1;
}
//main.c
#include <stdio.h>
int main()
{
int arg = 412;
int res ;
printf("start\n");
res = func_a(arg)+func_b(arg)+func_c(arg);
printf(" %d => %d \n" , arg , res );
samefun();
return res;
}