The use of dynamic libraries under Linux is very common and very useful.
Step One:
Create a. h header file that declares a function in the dynamic library in a header file
#ifndef _test_h_#define _test_h_#ifdef __cplusplus /*c C + + mixed programming */extern "C" {#endif <span style= " Font-family:arial, Helvetica, Sans-serif; >/*c C + + mixed programming */</span>int max (int a, int b), int add (int a, int b), #ifdef __cplusplus <span style= "Font-fam Ily:arial, Helvetica, Sans-serif; >/*c C + + mixed programming */</span>} #endif <span style= "font-family:arial, Helvetica, Sans-serif;" >/*c C + + mixed programming */</span> #endif
Step Two :
Creating a. c file implements a function in the header file
int max (int a, int b) { if (a > B) { return A; } else{ return b;} } int add (int a, int b) { return a+b;}
Step Three:
<span style= "White-space:pre" ></span> write Makefile file, add-shared parameter in compile command
<span style= "White-space:pre" ></span> adding-fpic parameters to the link command
<span style= "White-space:pre" ></span><pre style= "LINE-HEIGHT:28PX; White-space:pre-wrap; Color:rgb (105, 105, 105); Background-color:rgb (255, 255, 255); " ><pre style= "WHITE-SPACE:PRE-WRAP;" ><span style= "FONT-SIZE:14PX;" ><span style= "Color:rgb (255, 0, 0); ><span style= "White-space:pre" ></span>-shared:</span> this option specifies the build dynamic connection library; <span style= "Color:rgb (255, 0, 0); " > -fpic:</span> is compiled to <span style= "Color:rgb (255, 0, 0);" > Location Independent (Address-free) </span> code, without this option, the compiled code is location-dependent, so dynamic loading is the way code is copied </span>
-L: Specifies the path of the link library,-L. Indicates that the library to be connected is-ltest in the current directory : Specifies that the name of the link library is test and that the compiler has an implicit naming convention when looking for a dynamic connection library, that is, precede the given name with Lib, followed by. So to determine the name of the library
-wl,-rpath: path information for so files since logging. Ld_library_path: This environment variable indicates that the dynamic connector can load the path of the dynamic library . of course, if you have root permissions, you can modify the/etc/ld.so.conf file, and then call/sbin/ldconfig to achieve the same purpose,
However, if you do not have root privileges, then you can only modify the LD_LIBRARY_PATH environment variable method.
. SUFFIXES:.C.OCC = GCCSRC = TEST.COBJK = $ (src:.c=.o) EXEC = Libtest.sostart: $ (OBJK) $ (CC)-shared-o $ (EXEC) $ (OBJK ) @echo---------------OK-------------------. c.o: $ (CC)-wall-fpic-g-o [email protected]-C $< Clean: Rm-f $ (OBJK) Rm-f $ (EXEC) rm-f core.*
Use this dynamic library
Making libxxx.so dynamic libraries under Linux