概述
在C语言中,库分为静态库(.a)和动态库(.dll或.so),库文件其实是编译好的源代码,配合相应的头文件方便他人使用,避免被随意篡改,读取源代码。
调用静态库时,编译器会把库文件编译到可执行文件(.exe)里,可以在其他地方单独运行可执行文件;
调用动态库时,编译器不会把库文件编译到可执行文件(.exe)里,需要同可执行文件放到指定位置,程序运行时才会调用;相应的便利是,更新动态库可以实现对程序的部分更新。
下载配置MinGW
下载地址:https://winlibs.com/
解压到你想要的目录上,将 path/to/mingw64\bin 添加到系统变量path里;
Win键+R,输入cmd,进入后输入gcc -v,验证安装成功。
生成静态库及应用
- 在工作区,按住shift右击选择:在此处打开命令窗口,创建项目目录:
mkdir test_create_libs
cd test_create_libs
- 创建程序入口文件:
notepad main.c
写入:
#include <stdio.h>
int main(int arg,char *argv[])
{
printf("Hello World!");
return 0;
}
- 创建运行脚本:
notepad run.cmd
写入:
gcc -o main main.c
main
pause
*** 到此,双击运行脚本run.cmd就得到了一个 Hello World。
- 创建一个测试用的头文件:
mkdir include
notepad include/mylib.h
写入:
#if !defined(MYLIB_H)
#define MYLIB_H
void mylib_print();
#endif // MYLIB_H
- 创建一个实现的源代码文件:
mkdir src
notepad src/mylib.c
写入:
#include "../include/mylib.h"
#include <stdio.h>
void mylib_print(){
printf("Hello @ mylib");
}
- 修改入口文件:
notepad main.c
修改为:
#include <stdio.h>
#include "include/mylib.h"
int (int arg,char *argv[])
{
printf("Hello World @main.c\n");
mylib_print();
return 0;
}
- 键入命令调试:
gcc -o main main.c src/mylib.c
main
*** 到此,就得到了一个调用其他源文件的程序。
*** #include “…/include/mylib.h” 双引号表示引入本项目的头文件;
#include <stdio.h> 尖括号表示引入编译器里的头文件,可以把第三方的头文件和库文件分别复制到编译器里的include和lib文件夹,伪装成编译器的标准头文件。
- 将C源文件编译为对象文件。使用 -c 选项告诉GCC只编译不链接。
gcc -c -fPIC src/mylib.c -o mylib.o
- 使用 ar 命令将对象文件打包成静态库。
ar rcs libmylib.a mylib.o
- 编译时链接库,而不是src/mylib.c。
gcc -o main main.c -L. -lmylib
- 键入命令调试:
main
*** 到此,就得到了一个调用其他静态库的程序。
*** libmylib.a要同mylib.h一起使用,并且要在源代码中引入:
#include "mylib.h"
*** 这里 -L. 表示在当前目录(.)中查找库, -L./lib 表示在当前目录里的lib文件夹;
-lmylib告诉链接器链接libmylib.a(注意在 -l 选项中省略了 lib 前缀和 .a 后缀)
等同于:
gcc -o main main.c -L. libmylib.a
生成动态库及应用
- 在Windows上:
编译源文件为DLL
gcc -shared -o libmydll.dll src/mylib.c
- 在Unix-like系统上:
编译源文件为共享对象
gcc -shared -fPIC -o libmydll.so src/mylib.c
- 键入命令调试:
gcc -o main main.c -L. -lmydll
main
*** 到此,就得到了一个调用其他动态库的程序。
*** 动态库文件需要同可执行文件放到同一目录。