How to force gcc to link an unused static library How to force gcc to link an unused static library c c

How to force gcc to link an unused static library


Use --whole-archive linker option.

Libraries that come after it in the command line will not have unreferenced symbols discarded. You can resume normal linking behaviour by adding --no-whole-archive after these libraries.

In your example, the command will be:

g++ -o program main.o -Wl,--whole-archive /path/to/libmylib.a

In general, it will be:

g++ -o program main.o \    -Wl,--whole-archive -lmylib \    -Wl,--no-whole-archive -llib1 -llib2


The original suggestion was "close":

Try this: -Wl,--whole-archive -lyourlib


I like the other answers better, but here is another "solution".

  1. Use the ar command to extract all the .o files from the archive.

    cd mylib ; ar x /path/to/libmylib.a
  2. Then add all those .o files to the linker command

    g++ -o program main.o mylib/*.o