Linux动态链接库的使用
作者:fariver 时间:2023-09-21 19:56:55
动态链接库与普通的程序相比而言,没有main函数,是一系列函数的实现。通过shared和fPIC编译参数生产so动态链接库文件。程序在调用库函数时,只需要连接上这个库即可。例如下面实现一个简单的整数四则运输的动态链接库,定义的caculate.h和caculate.c两个文件,生产libcac.so动态链接库。
针对二进制文件有用的命令
查看文件类型
file
查看二进制文件链接到哪些库
ldd
查看二进制文件里面所包含的symbol,T表示加载,U表示undefined symbol
nm
读二进制文件里面的信息
readelf -a smu.o
将二进制文件转换为汇编
objdump -d sum.o
动态链接库的生成
sum.c
#include <stdio.h>
#include <stdlib.h>
int sum(int x){
int i, result=0;
for(i=0; i<=x; i++){
result+=i;
}
if(x > 100)
exit(-1);
return result;
};
void display(char* msg){
printf("%s\n",msg);
}
int add(float a,float b){
return a+b;
}
int sum_array(int array[], int num){
int i =0, sum = 0;
for(i=0; i<num; ++i)
sum += array[i];
return sum;
}
void modify_array(int array[], int num){
int i =0, sum = 0;
for(i=0; i<num; ++i)
array[i] *= 10;
}
main.c
#include <stdio.h>
#include <stdlib.h>
int main(void){
int x;
printf("Input an integer:\n");
scanf("%d", &x);
printf("sum=%d\n", sum(x));
return 0;
};
生成可执行文件
gcc -c main.c -o main.o
gcc -c sum.c -o sum.o
gcc sum.o main.o
将会生成main的可执行文件
file main // ELF 64-bit LSB executable
file sum.o // ELF 64-bit LSB relocatable
因为sum.c里面含有可复用的函数,所以想把sum.c编译成为一个动态链接库
gcc sum.o -shared -o sum.so
出现错误,提示
/usr/bin/ld: sum.o: relocation R_X86_64_PC32 against undefined symbol `exit@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
这说明不是所有的.o文件都能编译成为动态链接库,需要在.o文件生成时加参数-fPIC
gcc -c sum.c -fPIC -o sum.o
gcc sum.o -o shared sum.so
一般,共享库的编译命令为(曾经的实验)
动态链接库
gcc -shared -fPIC -o libmyhello.so hello.o
gcc -o hello main.c -L. -lmyhello
静态链接厍
ar rcs libxx.a xx.o
g++ -o main main.cpp -static -L. -lxx
这时候再
g++ -o main main.c sum.so
./main
有时会报错
error while loading shared libraries: sum.so: cannot open shared object file: No such file or directory
ldd main
output:
sum.so => not found
这时候需要
export $LD_LIBRARY_PATH=pwd:$LD_LIBRARY_PATH
注意:-fPIC是生成.o时使用,-shared是用来生成动态链接库的
来源:https://www.cnblogs.com/fariver/p/6560885.html


猜你喜欢
开心网广告收入月均700万 两轮融资2300万美元
从网站内部结构着手 谈音乐网站怎么做SEO
女站长做站有感
新手部署DNS服务器须知
Linux 中的防火墙 ufw 简介
Linux 中的export与alias命令详解
Windows 2000中任务时间表的帐号问题
使用shell脚本来给mysql加索引的方法
在VMware上创建虚拟机及安装Redhat Linux操作系统(图文教程)

预览WordPress 3.3
《谷歌搜索引擎优化初学者指南》昨日推出
一步步教你做支付宝与Wordpress的系统集成
网站擅播奥运节目赔30万
链接在搜索引擎优化得分 质量才是硬道理
Win2008系统活动目录权限管理服务
支付宝已获外管局批准 人民币可直购国外货物
美图秀秀 新增时尚图片特效与气泡提示

微软计划推迟Visual Studio 2010发布时间
美国主机webhostingpad介绍

揭开Google暴利秘密的数学公式
