6

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?

jeffreyveon
  • 13,400
  • 18
  • 79
  • 129

3 Answers3

4

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.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • Is it better practice to have the linker include or not include the comment record when building a library? – nwfistere May 03 '23 at 12:49
1

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.

Community
  • 1
  • 1
dlasalle
  • 1,615
  • 3
  • 19
  • 25
-2

A static library is completely included in the using program during compile time, so that it won't need any additional file to run the program.

If library A was already build with the static library B, A has B already and won't need it again.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • 1
    I don't think this is correct. A static library can still have unresolved dependencies which the linker will complain about. Each library during compilation will need access to at least the header files of its dependent libraries during that libraries compilation phase, however no attempt will be made to link to the dependant library as this could cause a project to include multiple copies of the same libraries, static library project don't have a linking phase. – PaulHK Apr 03 '17 at 07:16
  • @PaulHK And when exactly the already compiled static library A will complain about anything? If A is already compiled, B's part is done. And to use A in some full program, it has to be compiled. – deviantfan Apr 03 '17 at 09:40
  • 3
    Library A won't complain about its dependencies until it's included in a project that has a linker pass. Compiling a library does not require linking to any dependent library, hence why I mentioned the library only needs access to the dependant library headers, not its object files. – PaulHK Apr 03 '17 at 09:44