0

I am making a C++ library. In the library, I am using some functions in another static library (e.g. ref.a).

I want to generate one library file, either mylib.a or mylib.so, so that any program using my library does not need to link to the static library (ref.a). I got some ideas from others how to link static lib into dynamic lib, like "--whole-archive", but not so clear how to do it.

To get mylib.a, I just ar -rc mylib.a mylib.o ref.a (may not be a standard way). What about a shared lib, e.g. mylib.so?

Community
  • 1
  • 1
ubc_ben
  • 163
  • 1
  • 10

1 Answers1

2

To get mylib.a, I just ar -rc mylib.a mylib.o ref.a

No, that wouldn't work. You have to "expand" ref.a before you include it into mylib.a:

mkdir tmp.$$ && cd tmp.$$ && ar x ../ref.a &&
cd .. && ar rc mylib.a mylib.o tmp.$$/*.o &&
rm -rf tmp.$$

What about a shared lib

That's simpler:

gcc -shared -o mylib.so mylib.o -Wl,--whole-archive ref.a -Wl,--no-whole-archive

(It's very important to have the trailing -Wl,--no-whole-archive, or you may get nasty link errors from system libraries that the compiler driver adds to the end of the link.)

Employed Russian
  • 199,314
  • 34
  • 295
  • 362