Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using a C++ library that can be built as either a shared or a static library. This library uses a factory technique, where static objects register themselves when the program starts and the static objects get created.

This works fine as long as the shared library is used. When the static version is used, none of the static objects get included into the final program (because they aren't referenced directly) and thus their functionality isn't available.

Is there a way to force gcc to include all static objects from a library when linking?

The library is Open Source and I could modify it, if that helps.

like image 453
Gene Vincent Avatar asked Jan 22 '11 12:01

Gene Vincent


People also ask

Which gcc option is used to link the library?

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

Does gcc automatically link?

Most Windows compilers support auto-linking, as does Clang, while GCC does not support auto-linking.

What command is used to create a static library from object files gcc?

To create a static library, in general, we follow the 2-step method. First, we create object files for each source file using the 'gcc' command. Second, We will bundle all the object files using the 'ar' command.

What option should be added to a gcc command in order to link in functions from a library?

In addition, you must add the - lm flag to the gcc compiler command in order to use math functions in your C code.


2 Answers

You can use -Wl,--whole-archive -lyourlib , see the manpage for ld for more info.

Any static libraries mentioned after -Wl,--whole-archive on the command line gets fully included, you can turn this off again too if you need to , as in e.g. -Wl,--whole-archive -lyourlib -Wl,--no-whole-archive -lotherlib

like image 73
nos Avatar answered Oct 17 '22 06:10

nos


Use:

g++ -u <SYMBOL_NAME> ...

Note that -u is lowercase

like image 2
PA314159 Avatar answered Oct 17 '22 06:10

PA314159