How to Force Gcc to Link Unreferenced, Static C++ Objects from a Library

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

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

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

how can i force gcc to link a static library?

The explanation of the -u flag from GCC means the following:

If you have a symbol aka variable or function that is defined in your source tell
GCC to pretend that it is undefined so it takes the definition of such variable or
function from the library you are linking.

So if your B.c has nothing that may be defined in libA.a the -u flag won't help you since the symbol_A is not needed by B.c and by the same token B.o, so will be simply ignored.

Proper way to link a static library using GCC

Thanks for the replies! Turns out the problem was due to link order. Apparently, if you use a library which in turn has other library dependencies, those other dependencies must be listed after the library, not before as I had been doing. Learned something new!

Can you force unreferenced code to be linked in from a static library?

You can use the class class method on it, which will mostly be a no-op, but will reference it from your code.

int main(int argc, const char** argv)
{
[MyClass class]; // There you are! MyClass is now referenced from your code.

/* ... rest of your main function ... */
}

How to force gcc compiler/linker to remove from executable unused static arrays

One way might be to declare specialisations of a template function, each of which return the data, and the unused inline functions would not be compiled; however that might mean the array is created on the fly. Could you package your character font definitions into an int64, and make it pure code?



Related Topics



Leave a reply



Submit