创建动态库的简单例子,这里创建动态库是使用直接在终端敲命令的方式,并没有使用到VScode的一些配置文件、编译脚本啥的。
C程序的编译分为预处理、编译、汇编、链接。动态库其实就是第三个阶段编译的产物。minGW中包含的编译工具就是GCC,这个例子就是使用gcc这个工具去编译我们写的C代码。
动态库创建
- 新建文件夹test,创建源文件hello.c
#include<stdio.h>
int helloworld(){
printf("hello world");
return 0;
}
- 创建头文件hello.h,在头文件中定义函数
#include<stdio.h>
int helloworld();
- 使用命令创建动态库dll
进入终端,在.c文件所在文件夹下运行如下编译命令,会生成hello.o、hello.dll文件,hello.dll就是动态库了。-c参数:编译和汇编,但不链接,-o 参数:指定输出文件。
PS D:\Developer\WorkSpace\VSCode\projects\test> gcc -c hello.c -o hello.o
PS D:\Developer\WorkSpace\VSCode\projects\test> gcc hello.o -o hello.dll -shared
动态库的引用
创建main.c
#include <stdio.h>
#include "hello.h"
int main()
{
helloworld();
return 0;
}
在main中引用动态库hello.dll,这里要注意第二个参数hello(动态库名)前要加-l。-L指定库的搜索路径,-l指定库名。
PS D:\Developer\WorkSpace\VSCode\projects\test> gcc -c main.c -o main.o
PS D:\Developer\WorkSpace\VSCode\projects\test> gcc main.o -L. -lhello -o main.exe
生成可执行文件main.exe
运行main.exe,得到结果