欢迎光临
我们一直在努力

linux动态链接

1, 编译,使用-shared和-fpic 生成动态链接库
库源码:test.c

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

static void printline(int len)
{

    int i;

    for(i = 0;i<len;i++)
    {
        printf("=");        
    }
    printf("\n");
}

void print(char * s)
{   
    int len = 0;
    int  i = 0;
    if(!s || *s == '\0')
    {
        return ;
    }

    len = strlen(s);
    printline(len);
    printf("%s\n",s);
    printline(len);
}

头文件:test.h

#ifndef __TEST_H__
#define __TEST_H__

void print(char * s);

#endif

编译库文件:

gcc test.c -shared -fpic -o libtest.so

2.编译测试代码

测试代码:main.c

#include "test.h"

int main()
{
    char teststr[] = "hello world";

    print(teststr);

    return 0;

}

编译测试代码

    gcc  main.c -L./ -ltest -o main

3.运行

当运行时,发现找不到库文件
./main: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory

这个是linux库文件搜索路径的问题,有两个解决方式

  1. 在/etc/ld.so.conf.d/下编写配置文件,指定库路径,然后使用ldconfig去刷新缓存
  2. 在执行前设置环境变量 LD_LIBRARY_PATH,指定当前的路径,再去执行时,则现在本地去搜索
root@GFD:~/workspace/so_test# export LD_LIBRARY_PATH=./
root@GFD:~/workspace/so_test# ./main
===========
hello world
===========
赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。