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":

  • How to force gcc to link unreferenced, static C++ objects from a library

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
    

If there is a specific function in the static library that is stripped by the linker as unused, but you really need it (one common example is JNI_OnLoad() function), you can force the linker to keep it (and naturally, all code that is called from this function). Add -u JNI_OnLoad to your link command.