首先我们必须得知道动态链接库没有main函数,通过shared和fPIC编译参数生产so动态链接库文件。程序在调用库函数时,只需要连接上这个库即可。下面演示下:
首先是list.h 文件
#ifndef _LIST_H_
#define _LIST_H_
#include <string.h>
typedef struct _node_s
{
void * pdata; //头检点的数据域
struct _node_s *pnext;
}NODE_T,*pNode;
pNode list_init(void *data);
void list_add(pNode pHead,void *data);
int list_del(pNode pHead,int iIndex );
pNode list_getNode(pNode pHead,int index);
void* list_getNodeData(pNode pHead,int index);
int list_count(pNode pHead);
#endif
接下来是list.c文件
#include "list.h"
pNode list_init(void *data)
{
pNode pHead = NULL;
//1.申请一个节点
pHead = malloc(sizeof(pNode));
if(NULL == pHead)
{
printf("malloc faild! \n");
getchar();
// exit(-1); //程序退出
}
//2.初始化节点信息
//memset(pHead,0,sizeof(pNode));
pHead->pdata = data;
pHead->pnext = NULL;
return (pHead);
}
void list_add(pNode pHead,void *data)
{
pNode pNew = list_init(data);
if(pHead->pnext==NULL)
{
pHead->pnext=pNew;
}
else
{
while(pHead->pnext!=NULL)
{
pHead=pHead->pnext;
}
pHead->pnext=pNew;
}
}
int list_del(pNode pHead,int iIndex )
{
pNode p = pHead->pnext,p1 = pHead; //p1下一个结点永远是p
int count = 0; //用来计结点
//直到结点为空时结束循环
while(p != NULL)
{
count++;
//1.一遍遍历过去找到iIndex
if(count == iIndex)
{
//2.重新串接借调
p1->pnext = p->pnext;
//3.释放内存空间
free(p->pdata); //释放p的data
free(p); //释放完p的data还有p
return 1; //释放成功
}
p1 = p1->pnext;
p = p->pnext;
}
return -1; //删除失败
}
pNode list_getNode(pNode pHead,int index)
{
int count = 1;
pNode pTemp = pHead->pnext;//从下一个节点开始查找
while(pTemp != NULL) //找到该节点
{
if(index == count)
{
return pTemp;
}
pTemp = pTemp->pnext;//指向下一个节点
count++;//节点序号++
}
return pTemp; //没找到返回NULL
}
void* list_getNodeData(pNode pHead,int index)
{
int count = 1;
pNode pTemp = pHead->pnext;//从下一个节点开始查找
while(pTemp != NULL) //找到该节点
{
if(index == count)
{
return pTemp->pdata;
}
pTemp = pTemp->pnext;//指向下一个节点
count++;//节点序号++
}
return NULL; //没找到返回NULL
}
int list_count(pNode pHead) //pHead是局部变量参数,和外面没有关系
{
int count = 0;
while(pHead != NULL)
{
pHead= pHead->pnext;
count++;
}
return count;
}
编译生产libcac.so文件如下: gcc -shared -fPIC list.c -o liblist.so
下面是test.c文件
#include <string.h>
#include "list.h"
typedef struct student
{
int id;
char name[20];
}S;
int main()
{
pNode p;
p = (pNode )LIST_Init(NULL);
S *people = NULL;
S *people1 = NULL;
S *people3 =NULL;
people = (S *)malloc(sizeof(S));
people->id = 1;
strcpy(people->name,"gao");
people1 = (S *)malloc(sizeof(S));
people1->id = 2;
strcpy(people1->name,"chen");
people3 = (S *)malloc(sizeof(S));
people3->id = 3;
strcpy(people3->name,"chen");
LIST_Add(people,p);
LIST_Add(people1,p);
LIST_Add(people3,p);
while(p->pnext!=NULL)
{
p = p->pnext;
S *s =(S*)(p->pdata);
printf("id:%d ",s->id);
printf("name:%s\n",s->name);
}
}
编译生产可执行文件main如下:gcc test.c -o test -L ./ -llist (其中-L指明动态链接库的路径,-l后是链接库的名称,省略lib)
执行前必须设置环境变量:输入export LD_LIBRARY_PATH="./$LD_LIBRARY_PATH"
最后执行文件:./test
程序执行结果如下所示: