温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

linux动态链接

发布时间:2020-08-04 00:10:27 来源:网络 阅读:541 作者:onecan2009 栏目:系统运维

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
===========
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI