如何在Visual Studio Code中配置MSVC构建C++静态库与动态库
问题根因
你当前的tasks.json配置默认生成.exe可执行文件,可执行文件要求必须有main函数作为程序入口,你编译的是纯库代码没有main函数,因此触发LNK1561报错。
第一步:修改头文件适配编译/调用场景
你当前的头文件硬编码了__declspec(dllexport),后续调用库时需要改为__declspec(dllimport),通过宏判断可以实现一份头文件同时适配两种场景:
#ifdef HELLOWORLD_EXPORTS #define HELLOWORLD_API extern "C" __declspec(dllexport) #else #define HELLOWORLD_API extern "C" __declspec(dllimport) #endif HELLOWORLD_API void connect(); HELLOWORLD_API int randNum(); HELLOWORLD_API int addNum(int a, int b);
第二步:更新tasks.json新增库编译任务
下面给出完整的tasks.json配置,包含4个可切换的任务:编译可执行文件、编译动态库(DLL)、编译静态库(LIB)、编译主程序并链接库:
{ "version": "2.0.0", "tasks": [ // 原有任务:编译带main入口的可执行文件 { "type": "shell", "label": "cl.exe build active executable", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/Fe:", "${fileDirname}\\${fileBasenameNoExtension}.exe", "${file}" ], "problemMatcher": ["$msCompile"], "group": "build" }, // 新增任务1:编译动态库DLL { "type": "shell", "label": "cl.exe build DLL", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/LD", // 指定生成动态库 "/D", "HELLOWORLD_EXPORTS", // 定义导出宏 "/Fe:", "${fileDirname}\\${fileBasenameNoExtension}.dll", "${file}" ], "problemMatcher": ["$msCompile"], "group": { "kind": "build", "isDefault": true } }, // 新增任务2:编译静态库LIB { "type": "shell", "label": "cl.exe build static LIB", "command": "cl.exe", "args": [ "/c", // 只编译不链接,生成obj文件 "/Zi", "/EHsc", "${file}", "/Fo:", "${fileDirname}\\${fileBasenameNoExtension}.obj" ], "problemMatcher": ["$msCompile"], "group": "build" }, { "type": "shell", "label": "lib.exe package static LIB", "command": "lib.exe", "args": [ "${fileDirname}\\${fileBasenameNoExtension}.obj", "/OUT:${fileDirname}\\${fileBasenameNoExtension}.lib" ], "dependsOn": ["cl.exe build static LIB"], // 依赖编译obj的任务 "problemMatcher": ["$msCompile"], "group": "build" }, // 新增任务3:编译主程序并链接库 { "type": "shell", "label": "cl.exe build main and link library", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/Fe:", "${fileDirname}\\${fileBasenameNoExtension}.exe", "${file}", "${fileDirname}\\helloworld.lib" // 替换为你的lib文件名,动态库/静态库通用 ], "problemMatcher": ["$msCompile"], "group": "build" } ] }
使用说明
- 编译动态库:打开你的库源码文件(如helloworld.cpp),按下Ctrl+Shift+B选择
cl.exe build DLL任务,执行完成后会在同目录生成.dll动态库、.lib导入库和.pdb调试文件 - 编译静态库:打开库源码文件,按下Ctrl+Shift+B选择
lib.exe package static LIB任务,执行完成后会生成静态.lib文件 - 链接库编译主程序:打开你的main.cpp文件,按下Ctrl+Shift+B选择
cl.exe build main and link library任务,执行完成后生成可执行文件。如果链接的是动态库,需要将.dll文件和.exe放在同一目录才能运行 - 每次运行任务前,请确保VS Code使用的终端是MSVC Native Tools Command Prompt,否则会找不到cl.exe、lib.exe工具
内容的提问来源于stack exchange,提问作者lesterjackson
相关产品推荐
相关产品推荐

