Linux动态链接库的建立

本文详细阐述了如何解决动态链接库文件在编译和运行时遇到的问题,包括添加链接库、配置环境变量等步骤,确保程序正确加载和执行。

hello.c

  1#include "hello.h"
  2 void hello()
  3 {
  4     printf("hello\n");
  5 }

hello.h

  1 #ifndef HELLO
  2 #define HELLO

  3 #include <stdio.h>
  4 void hello();

  5 #endif

test.c

  1 #include "hello.h"
  2 int main()
  3 {
  4     hello();
  5     return 0;
  6 }


1.创建动态链接库文件并编译

gcc -shared  hello.c  -o libhello.so
$gcc test.c
/tmp/cc8LkErr.o: In function `main':
test.c:(.text+0x12): undefined reference to `hello'
collect2: ld \u8fd4\u56de 1




不能找到函数hello

3添加链接库后编译

gcc test.c -lhello -L.

4.运行a.out

$ ./a.out 
./a.out: error while loading shared libraries: libhello.so: cannot open shared object file: No such file or directory

不能找到链接库libhello.so

5检测4的错误原因

$ ldd a.out 
	linux-gate.so.1 =>  (0x00110000)
	libhello.so => not found
	libc.so.6 => /lib/libc.so.6 (0x00879000)
	/lib/ld-linux.so.2 (0x00859000)


提示libhello.so这个库文件没有找到

6.添加环境变量

$ export LD_LIBRARY_PATH=/mnt:$LD_LIBRARY_PATH
./a.out
hello
7.现在检查

$ ldd a.out 
	linux-gate.so.1 =>  (0x00110000)
	libhello.so => /mnt/libhello.so (0x00111000)
	libc.so.6 => /lib/libc.so.6 (0x00879000)
	/lib/ld-linux.so.2 (0x00859000)

一切OK了

添加环境变量的方式有很多种

比如 /etc/ld.so.conf

    ~目下的.bash_profile都可以





                
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值