0
点赞
收藏
分享

微信扫一扫

设置静态、动态链接库

十日十月Freddie 2022-03-19 阅读 39
c语言

利用C语言实现阶乘函数f(n) = n!

  1. 将f(n)封装在静态库中,然后再编写另外一个C程序调用f(n)
  2. 将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;
}

使用静态链接库

如何生成静态库:

  1. gcc -c f.c (生成f.o文件)
  2. 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

如何使用动态库

如何生成动态库

  1. gcc -fPIC -c f.c(生成f.o文件)
  2. gcc -shared -o libf.so f.o(生成libf.so动态库)

如何链接动态库

  1. 将生成的libf.so文件拷贝到/usr/lib路径下
cp libf.so /usr/lib
  1. 将/usr/lib路径设置到环境变量LD_LIBRARY_PATH中,使得在按照该环境变量路径查找动态库时,编写的动态库能被找到
export LD_LIBRARY_PATH=/usr/lib
  1. gcc -o sh_test sh_ftest.c -lf

运行可执行文件

运行链接到静态库的可执行文件

./st_test 5

注释:计算 f(5) = 5!
运行链接到动态库的可执行文件

./sh_test 6

注释:计算 f(6) = 6!
在这里插入图片描述

举报

相关推荐

0 条评论