Windows/Linux下vscode+vcpkg管理C++包链接方法
1. 安装和设置 vcpkg
Windows:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
.\bootstrap-vcpkg.bat
.\vcpkg integrate install
Linux:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
2. VSCode 扩展安装
安装必要的扩展:
- C/C++ Extension Pack
- CMake Tools(如果使用 CMake)
3. 配置方式
方式一:使用 CMake(推荐)
创建 CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(MyProject)set(CMAKE_CXX_STANDARD 17)# 查找包
find_package(fmt CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)add_executable(main main.cpp)# 链接库
target_link_libraries(main PRIVATE fmt::fmt nlohmann_json::nlohmann_json)
配置 CMakePresets.json:
{"version": 3,"configurePresets": [{"name": "default","toolchainFile": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"}]
}
方式二:配置 c_cpp_properties.json
在 .vscode/c_cpp_properties.json
中配置:
Windows:
{"configurations": [{"name": "Win32","includePath": ["${workspaceFolder}/**","C:/vcpkg/installed/x64-windows/include"],"defines": ["_DEBUG","UNICODE","_UNICODE"],"windowsSdkVersion": "10.0.19041.0","compilerPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe","cStandard": "c17","cppStandard": "c++17","intelliSenseMode": "windows-msvc-x64"}],"version": 4
}
Linux:
{"configurations": [{"name": "Linux","includePath": ["${workspaceFolder}/**","/path/to/vcpkg/installed/x64-linux/include"],"defines": [],"compilerPath": "/usr/bin/gcc","cStandard": "c17","cppStandard": "c++17","intelliSenseMode": "linux-gcc-x64"}],"version": 4
}
4. 配置编译任务
创建 .vscode/tasks.json
:
Windows:
{"version": "2.0.0","tasks": [{"type": "shell","label": "C/C++: cl.exe build active file","command": "cl.exe","args": ["/Zi","/EHsc","/Fe:","${fileDirname}\\${fileBasenameNoExtension}.exe","${file}","/I", "C:\\vcpkg\\installed\\x64-windows\\include","/link","/LIBPATH:C:\\vcpkg\\installed\\x64-windows\\lib"],"group": {"kind": "build","isDefault": true}}]
}
Linux:
{"version": "2.0.0","tasks": [{"type": "shell","label": "C/C++: g++ build active file","command": "/usr/bin/g++","args": ["-g","${file}","-o","${fileDirname}/${fileBasenameNoExtension}","-I/path/to/vcpkg/installed/x64-linux/include","-L/path/to/vcpkg/installed/x64-linux/lib","-lfmt" // 根据需要添加具体库],"group": {"kind": "build","isDefault": true}}]
}
5. 环境变量设置
设置 VCPKG_ROOT
环境变量:
- Windows:
set VCPKG_ROOT=[your vcpkg installed path]
- Linux:
export VCPKG_ROOT=[your vcpkg installed path]
6. 使用示例
安装包:
vcpkg install fmt nlohmann-json
示例代码 main.cpp:
#include <fmt/core.h>
#include <nlohmann/json.hpp>int main() {fmt::print("Hello vcpkg!\n");nlohmann::json j;j["name"] = "vcpkg";j["version"] = "2024";fmt::print("JSON: {}\n", j.dump());return 0;
}
最佳实践建议
- 使用 CMake - 最灵活且跨平台兼容性好
- 创建 vcpkg.json - 在项目根目录创建依赖文件:
{"dependencies": ["fmt","nlohmann-json"] }
- 版本控制 - 将 vcpkg.json 加入版本控制,但排除 vcpkg_installed 目录
- 使用 manifest 模式 - 让 vcpkg 自动管理项目依赖
这样配置后,VSCode 就能正确识别和链接 vcpkg 管理的包了。