gcc和ld 中的參數 --whole-archive 和 --no-whole-archive

轉自gcc和ld 中的參數 --whole-archive 和 --no-whole-archive函數


首先 --whole-archive --no-whole-archiveld專有的命令行參數,gcc 並不認識,要通gcc傳遞到 ld,須要在他們前面加-Wl,字串。spa

--whole-archive 能夠把 在其後面出現的靜態庫包含的函數和變量輸出到動態庫,--no-whole-archive 則關掉這個特性。.net

好比你要把 liba.a  libb.a libc.a 輸出到 libabc.dll(或libabc.so)時應該這麼寫:命令行

libabc.dll:liba.c libb.a libc.acode

       gcc  -shared -o $@ -L. -Wl,--whole-archive -la -lb -lc -Wl,--no-whole-archiveblog

在--whole-archive做用下的庫裏不能有函數同名。get

 

下面有一個包含Makefile 和c的完整例子:io

#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;
}
相關文章
相關標籤/搜索