0

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.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Instead of hacking some half solution together, you really should look into things like pkg-config. – rubenvb Dec 23 '16 at 07:26
  • @rubenvb Thanks for the suggestion. I've actually already moved in a different direction with my library, but I still find the answer immensely useful to know. – merlin2011 Dec 23 '16 at 08:00

1 Answers1

1

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.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • I only needed this to work on Linux. This is a brilliant answer! I would have never have discovered it myself and I'm actually curious how you learned about this. – merlin2011 Dec 23 '16 at 06:49