Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why link libraries (like pthread) when they are in the right folder "/lib" and "/usr/lib"?

1. Why do we need to link the non standard libraries/include non standard header files when they are already present in the right folder

anirudh@anirudh-Aspire-5920:~/Documents/DUMP$ locate libpthread
/lib/libpthread-2.12.1.so
/lib/libpthread.so.0
/usr/lib/libpthread.a
/usr/lib/libpthread.so
/usr/lib/libpthread_nonshared.a
/usr/lib/xen/libpthread.a
/usr/lib/xen/libpthread_nonshared.a
anirudh@anirudh-Aspire-5920:

The man page of ld.so/ld-linux.so - dynamic linker/loader says that the necessary libraries required by a program are searched In the default path /lib, and then /usr/lib. When my library's .so file is already there in /lib folder then why do I need to link it exclusively. Also the -l option is used to link static libraries. but when I do pmap of the process I see that the dynamic library of pthread with .so extension is being used rather than the one with .a extension. Similarly

anirudh@anirudh-Aspire-5920:~/Documents/DUMP$ locate mysql.h
/usr/include/mysql/mysql.h
anirudh@anirudh-Aspire-5920:~/Documents/DUMP$

When it is already present in the folder /usr/include which is the standard folder for all header files then why do I need to include it exclusively using -I option.

like image 552
Durin Avatar asked Mar 06 '11 07:03

Durin


1 Answers

  1. Although the linker searches in /lib and /usr/lib for libraries requested, this does not mean that it automatically loads all of those libraries. Loading a library is a fairly expensive operation, so the linker only loads libraries it knows will be needed. -l is what tells it the library is needed. There are some OSes and toolchains which automatically try to figure out what libraries are needed based on directives in the headers (Visual C++ does this on windows), but this technique is not used on Linux.
  2. -l is used for both static and shared libraries. If both are present, the shared version will be used, unless -static is specified to the linker.
  3. If you #include <mysql/mysql.h>, the preprocessor will look in /usr/include/mysql/mysql.h for it. That is, the search is not recursive - if you specify <mysql.h> the preprocessor will look at /usr/include/mysql.h but not /usr/include/mysql/mysql.h.
like image 191
bdonlan Avatar answered Dec 09 '22 14:12

bdonlan