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
相关推荐
猫猫不是喵喵.2 分钟前
双亲委派机制与类加载过程
java·开发语言
布朗克16815 分钟前
Go入门到精通-22-同步原语
开发语言·后端·golang·同步原语
帅次28 分钟前
Kotlin Flow 与 StateFlow:UI 单向数据流基础
开发语言·ui·kotlin·stateflow·onlifecycle
十月的皮皮37 分钟前
stm20260719-STM32F103RCT6_HAL库_三人抢答器
c语言·stm32·单片机·嵌入式硬件·stm32cubemx·hal库
艾伦野鸽ggg44 分钟前
JavaScript 浏览器本地存储
开发语言·javascript·ecmascript
AOwhisky2 小时前
Python 学习笔记(第十一期)——运维自动化(上·后篇):进程级监控与子进程管理——psutil进阶
运维·开发语言·python·学习·云原生·运维开发
人工干智能2 小时前
Python 的链式调用:一连串的“点”调用
开发语言·python
wuyk5552 小时前
53.嵌入式开发中栈溢出的深度解析:从HardFault到解决方案
c语言·stm32·单片机
就不掉头发2 小时前
如何优化程序的性能
开发语言
手写码匠2 小时前
MCP协议从零实现:手写一个完整的 Model Context Protocol 服务器与客户端
开发语言·数据结构