gcc library file connection

 

Compile into an executable file

First of all, we have to compile test.c as the target file, this time we need to execute

gcc –c –I /usr/dev/mysql/include test.c –o test.o

link

Finally, we link all target files into executable files:

gcc –L /usr/dev/mysql/lib –lmysqlclient test.o –o test

The library files under Linux are divided into two categories: dynamic link library (usually ending with .so) and static link library (usually ending with .a). The difference between the two is only that the code required for program execution is running Dynamically loaded at time, or statically loaded at compile time.

Use static link library when forced link

By default, GCC prioritizes the use of dynamic link libraries when linking. Only when the dynamic link library does not exist, the static link library is considered. If necessary, the -static option can be added to compile to force the use of the static link library.

There are library files libmysqlclient.so and libmysqlclient.a required for linking in the /usr/dev/mysql/lib directory. In order to make GCC use only static link libraries when linking, you can use the following command:

gcc –L /usr/dev/mysql/lib –static –lmysqlclient test.o –o test

 

Search path sequence when linking static libraries:

1. ld will look for the parameter -L in the GCC command
2. Look for the environment variable LIBRARY_PATH of gcc
3. Look for the default directory /lib /usr/lib /usr/local/lib This was written in the program when compile gcc of

The search path sequence during dynamic linking and execution:

1. The dynamic library search path specified when compiling the target code
2. The dynamic library search path specified by the environment variable LD_LIBRARY_PATH
3. The dynamic library search path specified in the configuration file /etc/ld.so.conf
4. The default dynamic library search path /lib
5. The default dynamic library search path /usr/lib

 

About environment variables:


LIBRARY_PATH environment variable: specify the search path of the program static link library file
LD_LIBRARY_PATH environment variable: specify the search path of the program dynamic link library file

Guess you like

Origin blog.csdn.net/qq_37061368/article/details/112347962