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
相关推荐
Yolanda_20221 小时前
Python学习-第九部分-错误处理与异常处理
开发语言·python·学习
郝学胜-神的一滴1 小时前
Qt 高级编程 037:QSS按钮样式封神指南
开发语言·c++·qt·软件工程·用户界面
DFT计算杂谈1 小时前
SCIENTIFIC REPORTS 非 van der Waals可调二维磁性材料设计平台
开发语言·php
库拉库拉里1 小时前
深入理解 C# 异步编程:同步、Task.Wait () 与 await 的本质区别及实践指南
开发语言·c#
霍霍的袁1 小时前
【C++】string类 从 入门使用 到 底层深浅拷贝模拟实现
开发语言·c++·visual studio
酷在前行1 小时前
【R绘图】Nature Communications 半眼图复刻:分布、区间与多面板排版(保姆级教程)
android·开发语言·r语言
C++、Java和Python的菜鸟2 小时前
第10章 后端Web进阶(Maven高级)
开发语言·python
神罚天下ET2 小时前
.NET 新增功能系列文章——C# 中的新增功能
开发语言·c#·.net
所愿ღ2 小时前
SSM框架-Spring3
java·开发语言·笔记·spring
noipp3 小时前
推荐题目:洛谷 P3726 [AHOI2017/HNOI2017] 抛硬币
c语言·数据结构·c++·算法·编程·洛谷·luogu