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
相关推荐
Goober Airy27 分钟前
JS:将JS对象格式化为php语法形式(完美支持无unicode编码匹配的正则)
开发语言·前端·javascript
半桔35 分钟前
排序时间的复杂度和稳定性
c语言·数据结构·c++·算法·排序算法
墨楠。38 分钟前
C语言数据结构编程练习-排序算法
c语言·数据结构·学习
哟哟耶耶40 分钟前
css-根据不同后端返回值返回渲染不同的div样式以及公共组件设定
开发语言·前端·css
还是鼠鼠1 小时前
详细介绍:使用 Axios 上传图片文件
开发语言·前端·javascript·vscode·ajax·前端框架·bootstrap
嘻嘻哈哈的zl2 小时前
初阶数据结构:树---堆
c语言·数据结构
Victoria.a2 小时前
c++继承
开发语言·c++
OCR_API3 小时前
实名制-网络平台集成身份证实名认证接口/身份证查询-PHP
android·开发语言·php
Ai__Chi3 小时前
c语言对应汇编写法(以中微单片机举例)
c语言·汇编
来恩10033 小时前
C# 使用ADO.NET访问数据全解析
开发语言·c#·.net