动态库创建
打开新文件夹LAGDLL(创建lagdll)
1.创建源文件lagtm.c,在源文件中定义函数
#include <stdio.h>
double lagtime(double p[],double Q[],int tm,int x,int y)
{
double lag;
//降雨为时段降雨,求矩形的形心横坐标
double parea=0;
double pxs[x];//各时段降雨形心横坐标
double paxsum;
double qarea=0;
double qxs[y];
double qaxsum=0;//面积乘以
for(int i=0;i<x;i++){
parea+=p[i];
pxs[i]=(2*i+1.0)/2;
paxsum+=p[i]*pxs[i];
}
px=;
for(int i=0;i<y;i++){
qarea+=Q[i];
qxs[i]=(2*i+1.0)/2;//第一个时段
qaxsum+=Q[i]*qxs[i];
}
lag=(qaxsum/qarea-paxsum/parea)*tm;
return lag;
}
2.创建头文件lagtm.h,在头文件中定义函数
#include <stdio.h>
double lagtime(double p[],double Q[],int tm,int x,int y);
创建动态库dll
进入终端
进入.c文件所在文件夹
PS C:\Studydemo\LAGDLL> cd lagdll
PS C:\Studydemo\LAGDLL\lagdll
创建liblagtm.dll动态库
PS C:\Studydemo\LAGDLL\lagdll> gcc -c lagtm.c -o lagtm.o
PS C:\Studydemo\LAGDLL\lagdll> gcc lagtm.o -o liblagtm.dll -shared
动态库的引用
创建main.c
#include <stdio.h>
#include "lagtm.h"
int main()
{
double pp[]={1.8,10.3,14.7,3.4,1.6 };
int cal_tm=6;
double QQ[] = { 0,0,230,1120,1970,1340,843,600,440,320,230,180,140,110,80,50,40,20,0 };
int x = sizeof(pp) / sizeof(pp[0]);
int y = sizeof(QQ) / sizeof(QQ[0]);
double lagtm=lagtime(pp,QQ,cal_tm,x,y);
printf("lagtime is:%f\n",lagtm);
return 0;
}
在main中引用动态库liblagtm.dll
PS C:\Studydemo\LAGDLL\lagdll> gcc -c main.c -o main.o
PS C:\Studydemo\LAGDLL\lagdll> gcc main.o -L. -lliblagtm -o main.exe
生成可执行文件main.exe
运行main.exe,得到结果
PS C:\Studydemo\LAGDLL\lagdll> ./main.exe
lagtime is 23.837102
附
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "C/C++ Runner: Debug Session",
"type": "cppdbg",
"request": "launch",
"args": [],
"stopAtEntry": false,
"externalConsole": false,
"cwd": "c:/Studydemo/LAGDLL",
"program": "c:/Studydemo/LAGDLL/build/Debug/outDebug",
"MIMode": "gdb",
"miDebuggerPath": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
setting.json
{
"C_Cpp_Runner.cCompilerPath": "gcc",
"C_Cpp_Runner.cppCompilerPath": "g++",
"C_Cpp_Runner.debuggerPath": "gdb",
"C_Cpp_Runner.cStandard": "",
"C_Cpp_Runner.cppStandard": "",
"C_Cpp_Runner.msvcBatchPath": "",
"C_Cpp_Runner.useMsvc": false,
"C_Cpp_Runner.warnings": [
"-Wall",
"-Wextra",
"-Wpedantic"
],
"C_Cpp_Runner.enableWarnings": true,
"C_Cpp_Runner.warningsAsError": false,
"C_Cpp_Runner.compilerArgs": [],
"C_Cpp_Runner.linkerArgs": [],
"C_Cpp_Runner.includePaths": [],
"C_Cpp_Runner.includeSearch": [
"*",
"**/*"
],
"C_Cpp_Runner.excludeSearch": [
"**/build",
"**/build/**",
"**/.*",
"**/.*/**",
"**/.vscode",
"**/.vscode/**"
]
}
借鉴
[1] https://b log.csdn.net/qq_53744721/article/details/122902857