GCC build a dynamic link library (.so file): - shared options and -fPIC

Linux dynamic link library (shared object file, a shared object file) file suffix .so, which is a special target file (object file), can be loaded (link) came in as the program runs. The advantage of using a dynamic link library is: the program's executable file smaller, modular and easy to update, at the same time, more efficient use of memory efficiency.

GCC build a dynamic link library

If you want to create a dynamic link library, you can use the GCC -sharedoptions. Input file can be a source file, the target file or assembly file.

Also have combined -fPICoptions. -fPIC options applied to the compilation stage, tell the compiler to generate position independent code (Position-Independent Code); As a result, the generated code is no absolute address, the relative address all use, so the code can be loaded into the loader any location in memory, you can correct execution. This is the shared libraries required by the shared library is loaded, the location in memory is not fixed.

For example, to generate dynamic link library from the source file:

$ gcc -fPIC -shared func.c -o libfunc.so

 Build a dynamic link library from the object files:

$ Gcc -o -fPIC -c func.c func.o
$ Gcc -shared -o func.o libfunc.so

 -fPIC option to act on the compilation stage, you have to use this option when generating an object file to generate position independent code.

GCC dynamic link library linked to an executable file

If you want to link a dynamic link library into the executable file, you need to list the name of the dynamic link library on the command line, as specific and general way of source files, object files. Consider the following example:

$ gcc main.c libfunc.so -o app.out

 The compiled together into app.out main.c and libfunc.so, when app.out runs, dynamic-link library load libfunc.so.

Of course, we must ensure that the program can be found in the dynamic link library at runtime. You can link libraries in the standard directory, such as / usr / lib, or set an appropriate environment variables, such as LIBRARY_PATH. Different systems have different ways to load link libraries.

 

Guess you like

Origin www.cnblogs.com/liuzhenbo/p/11030946.html