成都网站建设设计

将想法与焦点和您一起共享

linux动态链接

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

创新互联主营珙县网站建设的网络公司,主营网站建设方案,成都app软件开发公司,珙县h5小程序开发搭建,珙县网站营销推广欢迎珙县等地区企业咨询

#include 
#include 
#include 

static void printline(int len)
{

    int i;

    for(i = 0;i

头文件: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
===========

当前名称:linux动态链接
文章源于:http://chengdu.cdxwcx.cn/article/jgpeoh.html