Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do statically linked libraries require linking with their dependencies?

I'm building an executable that depends on a static library A which in turn depends on a static library B. When I build my application, do I need to also link against B in my build script?

To be more specific, do I need to do -la -lb, or, just linking with A via -la is enough?

like image 288
jeffreyveon Avatar asked Oct 30 '22 09:10

jeffreyveon


2 Answers

You might or might not have to link with both libraries, depending on how A was built.

If A contains a linker comment record instructing the linker to also look in library B for symbols (typically included in one of the object files contained within A), you don't need to include B when you link. If A does not contain that comment record, you must include it yourself.

like image 105
1201ProgramAlarm Avatar answered Nov 13 '22 16:11

1201ProgramAlarm


If both A and B are static, then you have to link both, in order of A then B (-la -lb). See this reply for an explanation of the order.

A statically linked program includes the libraries its linked against inside of the executable.

Imagine your program calls foo() inside of A, and somewhere inside of A, bar() gets called. So if A becomes part of your program, you then have an undefined call to bar() in your program, which is why you need to link against B as well.

The exception to this is when a special Visual Studio pragma is used (#pragma comment(lib, libname)) as mentioned by @1201ProgramAlarm.

like image 32
dlasalle Avatar answered Nov 13 '22 17:11

dlasalle