Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force gcc to link an unused static library

Tags:

c++

c

gcc

g++

ld

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?

like image 794
Martin Avatar asked Jan 02 '13 03:01

Martin


People also ask

Does gcc automatically link?

When the -fsanitize=thread option is used to link a program, the GCC driver automatically links against libtsan . If libtsan is available as a shared library, and the -static option is not used, then this links against the shared version of libtsan .

Which gcc option is used to link the library?

The -l option tells gcc to link in the specified library.


2 Answers

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 
like image 73
Alex B Avatar answered Sep 20 '22 18:09

Alex B


The original suggestion was "close":

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

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

like image 23
paulsm4 Avatar answered Sep 22 '22 18:09

paulsm4