利用C语言实现阶乘函数f(n) = n!
- 将f(n)封装在静态库中,然后再编写另外一个C程序调用f(n)
- 将f(n)封装到动态库中,然后在编写另外一个C程序调用f(n).
实验环境:Vxbox虚拟机,CentOS
//文件名:f.c
//内容:实现f(n) = n!
#include<stdio.h>
int f(int n){
int count = 1;
int i;
for(i=1; i<=n; i++)
count = count * i;
return count;
}
//文件名:st_ftest.c
//内容:链接到静态库libf.a,实现f(n)函数调用
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
if(argc < 2){
printf("static_library test: parameter is not found!\n");
exit(1);
}
int n = atoi(argv[1]);
printf("**********using static library**********\n");
printf("f(%d) = %d\n", n, f(n));
return 0;
}
//文件名:sh_ftest.c
//内容:链接到动态库libf.so,实现f(n)函数调用
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
if(argc < 2){
printf("share_library test: parameter is not found!\n");
exit(1);
}
int n = atoi(argv[1]);
printf("**********using share library**********\n");
printf("f(%d) = %d\n", n, f(n));
return 0;
}
使用静态链接库
如何生成静态库:
gcc -c f.c
(生成f.o文件)ar -crsv libf.a f.o
(生成libf.a静态库)
如何链接静态库
(三选一)
gcc -o st_test st_ftest.c -lf
gcc -o st_test st_ftest.c -L. -lf
gcc st_ftest.c libf.a -o st_test
如何使用动态库
如何生成动态库
gcc -fPIC -c f.c
(生成f.o文件)gcc -shared -o libf.so f.o
(生成libf.so动态库)
如何链接动态库
- 将生成的libf.so文件拷贝到/usr/lib路径下
cp libf.so /usr/lib
- 将/usr/lib路径设置到环境变量LD_LIBRARY_PATH中,使得在按照该环境变量路径查找动态库时,编写的动态库能被找到
export LD_LIBRARY_PATH=/usr/lib
gcc -o sh_test sh_ftest.c -lf
运行可执行文件
运行链接到静态库的可执行文件
./st_test 5
注释:计算 f(5) = 5!
运行链接到动态库的可执行文件
./sh_test 6
注释:计算 f(6) = 6!