码迷,mamicode.com
首页 > 系统相关 > 详细

linux动态链接

时间:2018-02-01 14:41:33      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:环境   ++   turn   编写   error   obj   loading   strlen   string   

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
===========

linux动态链接

标签:环境   ++   turn   编写   error   obj   loading   strlen   string   

原文地址:http://blog.51cto.com/6306331/2067710

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!