I have a case where there are two libraries lib1 and lib2. lib2 has dependencies on lib1. In my case lib2 is basically a high level wrapper around the functions inside lib1. The final application is just going to use functions from lib2 by including the relevant header. How do I statically build the libraries and link them to the final program?
Asked
Active
Viewed 5,668 times
1 Answers
21
Static libraries are just archives of object (.o
) files, so you can't have embedded dependency information. Something like ar cr lib1.a foo.o bar.o [more object files]
will build your libraries.
Because there is no dependency information, your main program has to link both the libraries and it's important to link lib1
after lib2
when lib2
depends on lib1
(otherwise the linker won't find the symbols that are unresolved in lib2
). A linking step could therefore look like this (assuming you use gcc
and your libraries are in the current directory):
gcc -otest main.o -L. -Wl,-Bstatic -l2 -l1
-
+1 I thought the same but due to less experience in C I didn't answered. (Y) – Harneet Singh Aug 05 '17 at 12:19
-
@rici the linker is not in the scope of the standard. This is about the GNU linker. You can list the same library *twice* in an invocation if necessary. – Aug 05 '17 at 14:45
-
For libraries, it is possible to place them twice on the command line:`-l1 -l2 -l1` will handle references in either direction including mutual recursion. – rici Aug 05 '17 at 14:49
-
That's what I just wrote, responding to your now-deleted comment. – Aug 05 '17 at 14:50
-
Felix, libraries are not in scope but the linker is part of the implementation. The standard provides for translation units and a mechanism to run a complete program, so there must be something like a linker. – rici Aug 05 '17 at 14:56
-
As to the other, i misread your answer so i deleted the complaint. Typing on glass is slow, at least for me. Sorry for the confusion. – rici Aug 05 '17 at 14:57
-
4Isn't there a way to make `l2.lib` contain the `l1.lib` objects as well? So when linking to the parent project of `l2.lib` only `l2.lib` will be linked? – Royi Apr 20 '19 at 06:54