构建C语言静态库文件并调用的实战案例和详细步骤实现

准备源文件

calc.h

  • 定义加法:int add(int a, int b);
  • 定义减法:int sub(int a, int b);
#ifndef __CALC_H_
#define __CALC_H_

int add(int a, int b);
int sub(int a, int b);

#endif // __CALC_H_

calc.c

  • 简单的实现加法
  • 简单的实现减法
#include "calc.h"

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

int sub(int a, int b){
    return a - b;
}

show.h

#ifndef __SHOW_H_
#define __SHOW_H_

void show(int a, char* op, int b, int res);

#endif // __SHOW_H_

show.c

#include <stdio.h>
#include "show.h"

void show(int a, char* op, int b, int res){
    printf("%d %s %d = %d\n", a, op, b, res);
}
编译C源文件
gcc -c calc.c
gcc -c show.c
构建静态库
ar -r libmath.a calc.o show.o
使用静态库文件

main.c

#include <stdio.h>
#include "calc.h"
#include "show.h"


int main(){
    int a = 11;
    int b = 22;
    int res = add(a, b);
    show(a, "+", b, res);

    return 0;
}

编译并运行文件,此时把静态库文件也带上:

gcc main.c libmath.a -o main && ./main

输出结果如下:

11 + 22 = 33
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python私教

创业不易,请打赏支持我一点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值