The below are instructions for setting up vcpkg in a CMake based C++ project. I’ve done this enough times to warrant a post on this site, that I can look up quickly instead of having to load up my notes app.
Steps
1 – Create a folder named ThirdParty, if it doesn’t already exist.
2 – Add vcpkg to that newly created folder, as a git submodule
git submodule add https://github.com/Microsoft/vcpkg.git ThirdParty/vcpkg
3 – Add the submodule to your git repo
git add ThirdParty/vcpkg .gitmodules
git commit -m "Add vcpkg as submodule in ThirdParty"
git push
4 – Initialize the git submodule and run the bootstrap process
git submodule update --init --recursive
cd ThirdParty/vcpkg
./bootstrap-vcpkg.sh
5 – Build the CMake project, using the vcpkg cmake file to tell the project where the dependencies are:
cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=ThirdParty/vcpkg/scripts/buildsystems/vcpkg.cmake [other flags]
Note, to add packages to the project, run the following commands:
.\ThirdParty\vcpkg\vcpkg.exe new --application
vcpkg add port opencv
Note, to have the bootstrap process run as part of the CMake configuration process, add the following CMake code to your topmost CMakeLists.txt file:
if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
set(bootstrap_vcpkg_ext "bat")
else()
set(bootstrap_vcpkg_ext "sh")
endif()
execute_process(
COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/ThirdParty/vcpkg/bootstrap-vcpkg.${bootstrap_vcpkg_ext}"
RESULT_VARIABLE bootstrap_vcpkg_result
)
if(NOT bootstrap_vcpkg_result EQUAL 0)
message(FATAL_ERROR "Bootstrapping failed with code: ${bootstrap_vcpkg_result}")
else()
message(STATUS "Bootstrapping succeeded.")
endif()
set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/ThirdParty/vcpkg/scripts/buildsystems/vcpkg.cmake"
CACHE STRING "vcpkg toolchain file")
Note, The project definition has to come after the CMAKE_TOOLCHAIN_FILE variable declaration. This will trip you up if this is not in the right place.
Note, vcpkg may try to install packages on every file change or any change to CMakeLists.txt. If the packages are not changing between edits, consider setting the variable VCPKG_MANIFEST_INSTALL to “OFF”. This can be done as a variable in CMake or a setting in the CMakePresets.json file. For example:
{
"version": 6,
"cmakeMinimumRequired": { "major": 3, "minor": 30, "patch": 0 }, "configurePresets": [ { "name": "vcpkg_defaults", "cacheVariables": { "VCPKG_MANIFEST_INSTALL": "OFF" }
[…]