How to force gcc to link an unused static library

2019-01-05 01:38发布

I have a program and a static library:

// main.cpp
int main() {}

// mylib.cpp
#include <iostream>
struct S {
    S() { std::cout << "Hello World\n";}
};
S s;

I want to link the static library (libmylib.a) to the program object (main.o), although the latter does not use any symbol of the former directly.

The following commands do not seem to the job with g++ 4.7. They will run without any errors or warnings, but apparently libmylib.a will not be linked:

g++ -o program main.o -Wl,--no-as-needed /path/to/libmylib.a

or

g++ -o program main.o -L/path/to/ -Wl,--no-as-needed -lmylib

Do you have any better ideas?

标签: c++ c gcc g++ ld
4条回答
我想做一个坏孩纸
2楼-- · 2019-01-05 02:15

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
    
查看更多
欢心
3楼-- · 2019-01-05 02:23

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
查看更多
放我归山
4楼-- · 2019-01-05 02:24

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.

查看更多
干净又极端
5楼-- · 2019-01-05 02:30

The original suggestion was "close":

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

查看更多
登录 后发表回答