Is it possible to artificially induce object file extraction for a given static library?

49 Views Asked by At

I was recently reading this answer and noticed that it seems inconvenient for users to have to link static libraries in the correct order.

Is there some flag or #pragma I can pass to gcc when compiling my library so that my library's object files will always be included?

To be more specific, I want it to be case that the user can link my static library before another library that depends on it, and not wind up with unresolved symbols, in the same way that object files which are explicitly specified on the linker line are.

In particular, I am looking for solutions where the user of the library does not need to do anything special, and merely needs to pass -lMylibrary the way they would link any other library.

1

There are 1 best solutions below

1
On BEST ANSWER

Is there some flag or #pragma I can pass to gcc

No.

I want it to be case that the user can link my static library before another library that depends on it, and not wind up with unresolved symbols, in the same way that object files which are explicitly specified on the linker line are.

Ship your "library" as a single object file. In other words, instead of:

ar ru libMyLibrary.a ${OBJS}

use:

ld -r -o libMyLibrary.a ${OBJS} 

In particular, I am looking for solutions where the user of the library does not need to do anything special, and merely needs to pass -lMylibrary the way they would link any other library.

You can name your object file libMyLibrary.a. I believe the linker will search for it using the usual rules, but when it finds it, it will discover that this is an object file, and treat it as such, despite it being "misnamed". This should work at least on Linux and other ELF platforms. I am not sure whether it will work on Windows.