Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a linker know what all libraries to link?

From http://www.learncpp.com/cpp-tutorial/19-header-files/

enter image description here

How does the linker know that it needs to include the standard runtime library and for example the definitions of the functions declared in iostream are not present elsewhere?

Is there some mapping that facilitates the linking process?

To rephrase - If I include some file with only function declarations, how does any linker figure out where the function definitions are?

like image 356
Lazer Avatar asked Feb 12 '12 11:02

Lazer


2 Answers

If you use g++, it will always link the standard c++ library (-lstdc++).

To bypass it, you can use gcc and link a different library.

Edit: the linker doesn't figure out anything. The standard library is automatically linked, so there's nothing to figure out for the standard functions. If you just declare something that is not in STL and try to use it without the actual definition, the linker will fail. You have to manually link the library/.o.

like image 172
Karoly Horvath Avatar answered Sep 18 '22 23:09

Karoly Horvath


This is just one of the default settings for your linker. Generally, you can tell it not to link the standard libraries if you don't wish to use them.

And you always have to tell the linker explicitly to link in any additional libraries that your application makes use of. It isn't going to "figure out" where the function definitions based solely on included declarations.

like image 31
Cody Gray Avatar answered Sep 18 '22 23:09

Cody Gray