how to compile and link static/dynamic library in linux

 

for static library:

1) use gcc to compile the target files, for example:

     gcc –c Strlen.c Strnlen.c

2) generates the static library with the following command:

     ar –rc libstr.a Strlen.o Strnlen.o

3) how to use the static library

    when we need to generate the executable code ( header files of the static library should be included )base on the static library, use the following commands[http://dev.csdn.net/article/84/84562.shtm]

   gcc -o main1 -L/home/hcj/xxxxxxxx main.o libstr.a
    其 中-I/home/hcj/xxxxxxxx和-L/home/hcj/xxxxxxxx是通过-I和-L指定对应的头文件和库文件的路径。 libstr.a是对应的静态库的名称。这样对应的静态库已经编译到对应的可执行程序中。执行对应的可执行文件便可以对应得函数调用的结果。

 

for the dynamic library, use the following commands:

      [http://dev.csdn.net/article/84/84562.shtm]

      gcc  -fpic -shared -o libstr.so  Strlen.c Strnlen.c
      -fpic 使输出的对象模块是按照可重定位地址方式生成的。
      -shared指定把对应的源文件生成对应的动态链接库文件libstr.so文件。


动态库的分为隐式调用和显式调用两种调用方法:
隐式调用的使用使用方法和静态库的调用差不多,具体方法如下:
gcc -c -I/home/hcj/xxxxxxxx main.c
gcc -o main1 -L/home/hcj/xxxxxxxx main.o libstr.so  //这里是*.so

在这种调用方式中,需要维护动态链接库的配置文件/etc/ld.so.conf来让动态链接库为系统所使用,通常将动态链接库所在目录名追加到动 态链接库配置文件中。否则在执行相关的可执行文件的时候就会出现载入动态链接库失败的现象。在编译所引用的动态库时,可以在gcc采用 –l或-L选项或直接引用所需的动态链接库方式进行编译。在Linux里面,可以采用ldd命令来检查程序依赖共享库。

 

显式调用:

#include<dlfcn.h>

 

int (*pStrlenFun)(char* pStr);     //声明对应的函数的函数指针

 

   void *pdlHandle;
    char *pszErr;

    pdlHandle = dlopen("./libstr.so", RTLD_LAZY);  //加载链接库/libstr.so
    if(!pdlHandle)
    {
        printf("Failed load library/n");
    }
    pszErr = dlerror();
    if(pszErr != NULL)
    {
        printf("%s/n", pszErr);
        return 0;
    }

    //get function from lib
    pStrlenFun = dlsym(pdlHandle, "Strlen"); //获取函数的地址
    pszErr = dlerror();
    if(pszErr != NULL)
    {
        printf("%s/n", pszErr);
        return 0;
    }

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值