Reprint: http://hi.baidu.com/linuxlife/blog/item/0d3e302ae2384d3a5343c1b1.html
Linux under the dynamic library with. So as the suffix, I am also the first to use the dynamic library under Linux, write a little introductory step, so that later can be easily used.
First step: Writing a Linux library
File 1. Dynamic Library Interface file
Dynamic Library Interface File Getmaxlen.h
#ifndef _getmaxlen_h_
#define _getmaxlen_h_
int Getmaxlen (int *sel,int N);
#endif
File 2. Dynamic Library Program implementation file
Dynamic Library Program implementation file GETMAXLEN.C
#include "Getmaxlen.h"
int Getmaxlen (int *sel,int N)
{
int n1=1,n2=1;
for (int i=1;i<n;i++)
{
if (Sel[i]>sel[i-1])
{
N2 + +;
if (N2 > N1)
{
N1 = n2;
}
}
Else
{
N2 = 1;
}
}
return N1;
}
Step two: Compile and build the dynamic library
GCC Getmaxlen.c–fpic–shared–o libtest.so
The above command generates the dynamic library libtest.so, in order to not need to dynamically load the dynamic library, the command should start with a. so suffix.
–fpic: represents compiled to a location-independent code, without this option, the compiled code is location-dependent, so dynamic loading is a way of copying code to meet the needs of different processes, but not to achieve the purpose of real code segment sharing.
–shared: Indicates compilation into a dynamic library.
Step three: Using dynamic libraries
1. Using dynamic libraries at compile time
File 1. Dynamic Library using File test.c
Using dynamic library libtest.so, this file is named test.c
#include "Getmaxlen.h"
int main ()
{
int sel[] = {2,3,6,5,3,2,1,2,3,4,5,6,7,6,5};
int m;
m = Getmaxlen (sel,15);
printf ("%d", m);
return 0;
}
Compile command:
GCC test.c–l. –l test–o Test
–L: Indicates the directory where the dynamic library resides
-L: Indicates the name of the dynamic library, which is the name in the header lib and suffix. So, as in the dynamic library libtest.so The L parameter is-l test.
Test:
LDD test
LDD test the dynamic library used by the executable file
2. Dynamic load mode using dynamic Library
File contents:
Dynamic loading of dynamic libraries using
int main ()
{
void *handle = NULL;
Int (*getmaxlen) (int *sel,int N);
int sel[] = {1,2,5,4,5,8,6,5,9,5,4,5,4,1};
Handle = Dlopen ("./libtest.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));
}
Compile command:
GCC–LDL test1.c–o Test
Gcc-o test test.c./libmytools.so
Compiling and using of Linux dynamic Library