Writing and using dynamic libraries in linux
Example 1
Compile header files
Mylib. h
# Include <stdio. h>
Compile library files
Mylib. c
Void Print ();
# Include "mylib. h"
Void Print ()
{
Printf ("This is in my first dynamic lib call ");
}
Write test code
Main. c
# Include "mylib. h"
Int main ()
{
Print ();
}
Write README
Gcc-shared-fPIC mylib. c-o libcac. so
Gcc-fpic-shared mylib. c-o mylib. so
-FPIC: indicates that the compiled code is in a separate position. If this option is not used, the compiled code is location-related. Therefore, during dynamic loading, the code is copied to meet the needs of different processes, but cannot achieve the purpose of truly sharing code segments.
-Shared: indicates that the database is compiled into a dynamic library.
Gcc-o main. c-L./mylib. so
Gcc-o main test. c-L././mylib. so
Example 2
Compile header files
# Ifndef _ GETMAXLEN_H _
# Define _ GETMAXLEN_H _
Int getMaxLen (int * sel, int N );
# Endif
Compile library files
# Include "getmaxlen. h"
Int getMaxLen (int * sel, int N)
{
Int n1 = 1, n2 = 1, I = 1;
For (I; I <N; I ++)
{
If (sel [I]> sel [I-1])
{
N2 ++;
If (n2> n1)
{
N1 = n2;
}
}
Else
{
N2 = 1;
}
}
Return n1;
}
Write test code
# Include "getmaxlen. h"
# Include <stdio. h>
Int main ()
{
Int Sel [] = {2, 3, 6, 3, 2, 1, 2, 3, 4, 5, 7, 6, 5 };
Int m;
M = getMaxLen (Sel, 15 );
Printf ("% d", m );
Return 0;
}
Dynamic library file loading
# Include "getmaxlen. h"
# Include <stdio. h>
# Include <dlfcn. h>
Int main ()
{
Void * handle = NULL;
Int (* getMaxLen) (int * sel, int N );
Int sel [] = };
Handle = dlopen ("./mylib. so", RTLD_LAZY );
If (handle = NULL)
{
Printf ("dll loading error. \ n ");
Return 0;
}
GetMaxLen = (int (*) (int *, int) dlsym (handle, "getMaxLen ");
If (dlerror ()! = NULL)
{
Printf ("fun load error. \ n ");
Return 0;
}
Printf ("% d \ n", getMaxLen (sel, 15 ));
}
Write README
Gcc-shared-fPIC mylib. c-o libcac. so
Gcc-fpic-shared mylib. c-o mylib. so
-FPIC: indicates that the compiled code is in a separate position. If this option is not used, the compiled code is location-related. Therefore, during dynamic loading, the code is copied to meet the needs of different processes, but cannot achieve the purpose of truly sharing code segments.
-Shared: indicates that the database is compiled into a dynamic library.
Gcc-o main. c-L./mylib. so
Gcc-o main test. c-L././mylib. so
Gcc-fpic-shared getmaxlen. c-o mylib. so (used to dynamically load library files)
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.