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
相关推荐
wu_ye_m2 分钟前
学习c语言第34天 用函数每次输出+1,链式访问,int和void
c语言·学习·算法
C137的本贾尼3 分钟前
JDBC 编程:用 Java 连接 MySQL
java·开发语言·mysql
AI视觉网奇6 分钟前
three-bvh-csg glb分割
开发语言·前端·javascript
牢姐与蒯8 分钟前
c++数据结构之c++11(二)
开发语言·c++
凉、介9 分钟前
深入理解 ARMv8-A|Application Binary Interface (ABI)
c语言·笔记·学习·嵌入式·arm
z2005093011 分钟前
【linux学习】深入理解 Linux 进程间通信:管道的艺术与实现
linux·开发语言
lcj251113 分钟前
【stack、queue、deque、priority_queue】C++ 栈 / 队列 / 优先级队列全解析!手撕实现 + 二叉树层序遍历(附源码)
开发语言·c++·笔记
奋斗的小方22 分钟前
Java进阶篇1-2:泛型
java·开发语言·windows
say_fall24 分钟前
模拟量输入输出技术超详细知识点总结
linux·开发语言·嵌入式硬件·学习·php
我是一颗柠檬25 分钟前
C++最全面复习:从入门到精通(2026年)
开发语言·c++·visualstudio