简体   繁体   中英

Linking and Loading of static library

My question is how exactly the linker works.

  • I am linking an executable with multiple third-party static libraries. Out of those static libraries, only a few of them are used by the executable. In the above case, does linker links only to the libraries whose functions are referenced in the executable?
  • If a static library has multiple object files and only one is used by executable, does it only links to that object file? or its links to the whole static library but loads only the object file which is used?

For your first question if no symbols from a given library are used it will usually not be included in the final product. Regarding object files the linker likely won't even include full object files but only symbols that are actually referenced, though your linker may have flags that change this behavior and cause the entire library to be included.

... how exactly the linker works.

a)... does linker links only to the libraries whose functions are referenced in the executable?

b)... static library has multiple object files and only one is used by executable, does it only links to that object file?

It depends... on Linux there are two kinds of libraries... ".so", and the.a (archive).

example:

 /usr/lib/x86_64-linux-gnu/libgmpxx.a
 /usr/lib/x86_64-linux-gnu/libgmpxx.so

If you specify the.a in the link portion of your build command, only the contained object files referenced by your app will be linked (not the whole library). This executable is 'stand-alone', and every copy running has its own copy of any functions it uses.

If you specify the.so in the link portion of your build command, and your app is the first to use a particular ".so" lib, I believe your app will be briefly suspended during its start-up while the WHOLE ".so" lib is loaded.

If you specify the.so in the link portion of your build command, and your app is not-the-first to use this particular.so, then the loader will add to your app a mapping to the already-loaded-'.so' in system memory. (a much faster connection)

Executable's using.so's rely on the system to have loaded the.so libraries into memory, and to memory-map the library into the app memory and complete the links of the app to the required functions.

I believe your 'static library' corresponds to the use of ".a" (archive) library.

a) yes - the linker (sometimes linking-loader) 'finishes' when there are no more unresolved references (to objects or functions).

b) yes - see a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM