linux下编译动态库

#include <stdio.h>   //num.c

int add_num(int a, int b){
	return a+b;
}

int sub_num(int a, int b){
	return a-b;
}
#include <stdio.h>   //print.c

int print_num(int n){
	printf("result is %d\n", n);
	return 0;
}
#include <stdio.h>   //hw.c
#include <my_lib.h>
int main(){
	int ret=0;
	int a=8,b=5;
	ret=add_num(a,b);
	print_num(ret);
	ret=sub_num(a,b);
	print_num(ret);
	return 0;
}
#ifndef __MY_LIB_H__
#define __MY_LIB_H__

int add_num(int a, int b);
int sub_num(int a, int b);

int print_num(int n);
#endif

以上便是四个文件与编译过程。接下来说说编译遇到的情况

第一步,编译出动态库 gcc -o libnum.so -fPIC -shared num.c print.c 

1. -shared,众所周知啊,.so时share object的缩写。为了让gcc知道是在编译 .so而不是可执行文件,所以需要-shared

2. -fPIC,这是编译动态库必须的。可见黄色圈起来的地方,分开编译,没加-fPIC,就会报错,提醒重新编译。其实-fPIC是编译选项,PIC是 Position Independent Code 的缩写,表示要生成位置无关的代码,这是动态库需要的特性。

第二步,链接动态库,编译可执行文件 gcc -o test hw.c -I. -L. -lnum,没什么好说的

第三步,运行生成的可执行文件。

发现系统报错了。找不到libnum.so,原来Linux是通过/etc/ld.so.cache 文件搜寻要链接的动态库的。而 /etc/ld.so.cache 是 ldconfig 程序读取 /etc/ld.so.conf 文件生成的。
(注意,  /etc/ld.so.conf  中并不必包含 /lib 和 /usr/libldconfig程序会自动搜索这两个目录)

如果我们把 libnum.so 所在的路径添加到 /etc/ld.so.conf 中,再以root权限运行 ldconfig 程序,更新 /etc/ld.so.cache ,a.out运行时,就可以找到 libmum.so

但为此去改动系统的东西,不大行。

所以,我就搜了下还有啥办法,其实把 libnum.so添加到LD_LIBRARY_PATH就ok了,换句话说,就是把当前路径添加一下。

最简单办法自然就是export  LD_LIBRARY_PATH=LD_LIBRARY_PATH:$pwd。

不过这样重新打开时候还要再搞一遍,还不如写道 ~/.profile或者 ~/.bashrc好。source ~/.profile 就ok了

发布了10 篇原创文章 · 获赞 0 · 访问量 155

猜你喜欢

转载自blog.csdn.net/tjw316248269/article/details/104433343