# C/C++ Win10 VS Code 动态链接 DLL 的生成与使用
# C/C++ 基本配置
# VS code 插件
# 编译器选择
# 动态链接文件生成
# 1. 头文件 htest.h
1 2 3 4 5 6 7 8 9 10
| #ifndef HELLO_H #define HELLO_H #include <iostream>
void say_hello(); double add(double a,double b);
#endif
|
# 2. c++ 源码文件 Dlltest.cpp
需要把头文件放在同一目录下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <iostream> #include "htest.h"
using namespace std;
void say_hello(){ std::cout << "Hello, from DllTest!\n"; }
double add(double a,double b) { return a+b; }
|
# 3. CMakeLists.txt
自己写 Cmakelists 文件,也可以利用 cmake tools 生成库文件的模板
1 2 3 4 5 6 7 8 9
| cmake_minimum_required(VERSION 3.20) PROJECT(HELLOLIB) SET(SRC DllTest.cpp) ADD_LIBRARY(hello SHARED ${SRC}) SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
|
# 生成动态链接文件
从终端进入文件夹,新建 build 文件夹,进入后 cmake ..
以及 make
注意使用 make 命令可能需要配置
生成后 dll 文件在 lib 文件夹里:libhello.dll
# 动态链接文件的调用
vscode 中设置,参考官网教程 vscode C++ 教程
# 1.launch.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| { "version": "0.2.0", "configurations": [ { "name": "g++.exe - 生成和调试活动文件", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "C:\\Strawberry\\c\\bin\\gdb.exe", "setupCommands": [ { "description": "为 gdb 启用整齐打印", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "description": "将反汇编风格设置为 Intel", "text": "-gdb-set disassembly-flavor intel", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe 生成活动文件" } ] }
|
# 2.tasks.json
其中编译器 g++.exe 地址:C:\Strawberry\c\bin\g++.exe
头文件和动态链接的文件地址
E:\C++projects\Lib\include\htest.h
E:\C++projects\Lib\bin\libhello.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe 生成活动文件", "command": "C:\\Strawberry\\c\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe", "-I","E:\\C++projects\\Lib\\bin", "-L","E:\\C++projects\\Lib\\include", "-l","libhello" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "调试器生成的任务。" } ], "version": "2.0.0" }
|
# 3. 调用示例文件 dllExample.cpp
头文件 htest.h 和动态链接文件 libhello.dll 也可以放在同一文件夹下
1 2 3 4 5 6 7 8 9 10 11 12
| #include <iostream> #include "htest.h" using namespace std;
int main(int, char**){ double result; cout << "SayHello()" << endl; say_hello(); result=add(1.5,6.9); cout<<result<<endl; }
|
运行结果