Linux下生成动态库

  库本质上是一种可执行代码的二进制形式,可以被操作系统载入内存执行。Linux通常有两种库:动态库和静态库。下面说明Linux下动态库生成过程。

  假设一个socket功能的库,其头文件clt_socket.h,如下

#ifndef CLT_SOCKET_H
#define CLT_SOCKET_H
#include <stdlib.h>

int clt_socket_init (void **handle) ;

int clt_socket_send (void *handle, unsigned char *buf, int buflen) ;
int clt_socket_recv (void *handle, unsigned char *buf, int *buflen) ;

#endif

对应的实现文件clt_socket,c

#include "clt_socket.h"
#include "string.h"
#include <stdio.h>

typedef struct _SC_HANDLE {
    char version[16] ;
    char serverip[16] ;
    int  serverport ;
    char *buf ;
    int  buflen ;
} SC_HANDLE ;

int clt_socket_init (void **handle)
{
    SC_HANDLE *sh = NULL ;
    if ((sh = (SC_HANDLE*)malloc(sizeof(SC_HANDLE))) == NULL)
    {
        return -1 ;
    }
    strcpy(sh->version,"1.0.0") ;
    strcpy(sh->serverip, "192.168.1.1") ;
    sh->serverport = 8080 ;

    *handle = (void *) sh ;

    return 0 ;
}

int clt_socket_send (void *handle, unsigned char *buf, int buflen)
{
    int ret = 0 ;
    if (NULL == handle || NULL == buf)
    {
        ret = -1 ;
        printf("clt_socket_send error :%d", ret) ;
        return ret ;
    }

    SC_HANDLE *sh = NULL ;
    sh = (SC_HANDLE*)handle ;

    if ((sh->buf = (char*)malloc(buflen * sizeof(char))) == NULL)
    {
         ret = 2 ;
        printf("clt_socket_send malloc buflen:%d error : %d", buflen,ret) ;
        return ret ;
    }
    memcpy(sh->buf, buf, buflen) ;
    sh->buflen = buflen ;

    return ret ;
}

int clt_socket_recv (void *handle, unsigned char *buf, int *buflen)
{
    int ret = 0 ;
    if (NULL == handle || NULL == buf || NULL == buflen)
    {
        ret = -1 ;
        printf("clt_socket_recv  error :%d", ret) ;
        return ret ;
    }

    SC_HANDLE *sh = NULL ;
    sh = (SC_HANDLE*)handle ;
      
    memcpy(buf, sh->buf, sh->buflen) ;
    *buflen = sh->buflen ;

    return ret ;
}

为了将该功能封装生成动态库,需要先将其编译成目标代码:

gcc -o clt_socket.c

然后将生成库文件:

gcc -shared -fPIC -o libmysocket.so clt_socket.o

发现提示错误

什么情况?看提示。

在来重新编译过:

gcc -o clt_socket.c -fpic

ok.现在再来生成就OK了。

来测试一下看看生成的库是否可用:

//main.c

#include <stdio.h>
#include <string.h>

#include "clt_socket.h"

int main ()
{
    void *handle = NULL ;

    unsigned char buf[128] ;
    int buflen = 16 ;

    unsigned char outbuf[128] ;
    int outbuflen ;

    int ret = 0 ;
    strcpy(buf, "adddddddddddddcc") ;
    if (clt_socket_init(&handle) != 0)
    {
        printf("clt_socket_init err") ;
        ret = -1 ;
        goto end ;
    }

    if (clt_socket_send(handle, buf, buflen) != 0)
    {
        printf("clt_socket_send error") ;
        ret = -2 ;
        goto end ;
    }

end :
    return 0 ;
}
gcc -o test main.c -L. -lmysocket
./test

over!!!

posted on 2015-02-04 15:28  子墨sky  阅读(153)  评论(0)    收藏  举报

导航