C语言自定义库

  1. 编写 xx.c 和xx.h文件\
  2. 将源代码编译为目标文件 gcc -c add.c sub.c 执行完毕后会生产add.o和sub.o文件
  3. 静态库创建使用ar命令;
    ar -r libmymath.a add.o sub.o
  4. 将库和main.c文件一起编译 gcc -o main main.c -lmymath -L./

注意 上述书写格式不要错乱 -L 是指定文件路径

c 复制代码
#include"add.h"
int add(int a,int b)
{
    return a+b;
}
//add.h"
#ifndef C_ADD_H
#define C_ADD_H
int add(int a,int b);
#endif

//sub.c
#include"stdio.h"
int sub(int a,int b)
{
    return a-b;
}

//sub.h
#include"stdio.h"
int sub(int a,int b)
{
    return a-b;
}
c 复制代码
//main
#include"stdio.h"
#include"add.h"
#include"sub.h"

int main()
{
    int a=20,b=10;
    int c;
    c = add(a,b);
    printf("%d\n",c);
    return 0;
}

动态库制作

  1. 动态库对应的源文件 "test_lib.c"
  2. 动态库对应的头文件 "test_lib.h"
c 复制代码
gcc test_lib.c -fPIC -shared -o libtest.so

说明: -fPIC   :表示生成位置无关代码(PIC:Position Independent Code)
      -shared : 表示创建生成动态共享库


gcc test_bin1.c -L. -ltest -o test1

说明:编译的时候指定了libtest.so(上述编译好的动态库)
c 复制代码
//test_lib.c
#include "stdio.h"

void test_print(void) {
       printf("======= This is a test line.\n");
       return;
}



//test_lib.h
#ifndef __TEST_H
#define __TEST_H
void test_print(void);
#endif
相关推荐
ZTLJQ5 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
2401_891482176 小时前
多平台UI框架C++开发
开发语言·c++·算法
88号技师6 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751286 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神6 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
m0_726965987 小时前
面面面,面面(1)
java·开发语言
2401_831920747 小时前
分布式系统安全通信
开发语言·c++·算法
~无忧花开~7 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架
m0_488633328 小时前
C语言中枚举类型变量的定义、赋值及使用方法全解析
c语言·枚举类型·实例分析·变量定义·赋值使用
老鱼说AI8 小时前
大规模并发处理器程序设计(PMPP)讲解(CUDA架构):第四期:计算架构与调度
c语言·深度学习·算法·架构·cuda