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
相关推荐
gAlAxy...1 小时前
MyBatis-Plus 核心 CRUD 操作全解析:BaseMapper 与通用 Service 实战
java·开发语言·mybatis
开开心心就好1 小时前
一键加密隐藏视频,专属格式播放工具
java·linux·开发语言·网络·人工智能·macos
CUC-MenG1 小时前
Codeforces Round 1079 (Div. 2)A,B,C,D,E1,E2,F个人题解
c语言·开发语言·数学·算法
阿里嘎多学长1 小时前
2026-02-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
666HZ6661 小时前
数据结构4.0 串
c语言·数据结构·算法
Anastasiozzzz2 小时前
Java异步编程:CompletableFuture从入门到底层实现
java·开发语言
九.九2 小时前
高性能算子库 ops-nn 的底层架构:从调度到指令的极致优化
开发语言
比奇堡派星星2 小时前
sed命令
linux·运维·服务器·开发语言
船神丿男人2 小时前
C++:STL string(一)
开发语言·c++
程序员zgh2 小时前
Linux 内存管理单元 MMU
linux·运维·服务器·c语言·开发语言·c++