天天看點

gcc連結參數--whole-archive的作用

gcc連結參數--whole-archive的作用

// a.h

extern void foo();

// a.cpp

#include 

void foo()

{

    printf("foo\n");

}

// x.cpp

#include "a.h"

int main()

        foo();

        return 0;

// Makefile

all: x

x: x.cpp liba.so

g++ -g -o $@ $^

liba.so: liba.a

g++ -g -fPIC -shared -o $@ $^

#g++ -g -fPIC -shared -o $@ -Wl,--whole-archive $^ -Wl,-no-whole-archive

liba.a: a.o

ar cru $@ $^

a.o: a.cpp

g++ -g -c $^

clean:

rm -f x a.o liba.a liba.so

$ make

g++ -g -c a.cpp

ar cru liba.a a.o

g++ -g -fPIC -shared -o liba.so liba.a

#g++ -g -fPIC -shared -o liba.so -Wl,--whole-archive liba.a -Wl,-no-whole-archive

g++ -g -o x x.cpp liba.so

/tmp/cc6UYIAF.o: In function `main':

/data/jayyi/ld/x.cpp:5: undefined reference to `foo()'

collect2: ld returned 1 exit status

make: *** [x] Error 1

預設情況下,對于未使用到的符号(函數是一種符号),連結器不會将它們連結進共享庫和可執行程式。

這個時候,可以啟用連結參數“--whole-archive”來告訴連結器,将後面庫中所有符号都連結進來,參數“-no-whole-archive”則是重置,以避免後面庫的所有符号被連結進來。

g++ -g -fPIC -shared -o $@ -Wl,--whole-archive $^ -Wl,-no-whole-archive

繼續閱讀