CMake and vcpkg

Integrate vpckg and cmake-js

I missed how easy to install system wide library using apt, pkg, or brew. Something that missing in Windows. Fortunately, vcpkg exists. Unfortunately, it's not as easy as the other system wide package manager.

I successfully setup vcpkg to install system wide libraries, with these steps:

NOTE: Visual Studio must be already installed.

  1. Don't use Developer PowerShell from Visual Studio installation. Just use the general PowerShell.

    Developer PowerShell from Visual Studio will use embedded vcpkg which doesn't support system wide installation.

  2. Install vcpkg

    git clone https://github.com/microsoft/vcpkg "<path-to-vcpkg>"
    cd "<path-to-vcpkg>"
    .\bootstrap-vcpkg.bat
    .\vcpkg integrate install
  3. Edit User Profile to set environment variables

    You can edit the User profile in PowerShell with this command

    notepad $profile.CurrentUserCurrentHost

    then add these lines at the end of file

    # set vcpkg environment variable and path 
    $env:VCPKG_ROOT="<path-to-vcpkg>"
    $env:Path += ";$env:VCPKG_ROOT"
    
    # to set MSVC environment variables for x86_amd64 platform. 
    # This step assumes you installed Visual Studio 2022 Community edition for x86_64 platform
    & "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64

    restart or open new PowerShell session.

    to set environment variables for current session, you can reload the profile with this command

    . $PROFILE
  4. Edit your CMakeLists.txt

    Put these lines before the first project()

    if (WIN32)
        if (NOT DEFINED ENV{VCPKG_ROOT})
            message(FATAL_ERROR "$ENV{VCPKG_ROOT}: Env VCPKG_ROOT needs to be set!")
        endif ()
    
        set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake")
    endif ()

    at this step, Env variable VCPKG_ROOT must've been set as this is the necessary condition for our cmake to work.

  5. Now, you can install system wide libraries with vcpkg and use find_package, find_path, and find_library in CMakeLists.txt

    Example:

    • Install openssl, libssh2, and zlib

      vcpkg install openssl libssh2 zlib
    • use installed libs in CMakeLists.txt

      find_package(OpenSSL REQUIRED)
      target_link_libraries("${PROJECT_NAME}" PRIVATE OpenSSL::SSL OpenSSL::Crypto)
      
      find_package(ZLIB REQUIRED)
      target_link_libraries("${PROJECT_NAME}" PRIVATE ZLIB::ZLIB)
      
      find_library(LIBSSH2_LIBRARY NAMES ssh2 libssh2)
      find_path(LIBSSH2_INCLUDE_DIR NAMES libssh2.h)
      target_link_libraries("${PROJECT_NAME}" PRIVATE "${LIBSSH2_LIBRARY}")
      target_include_directories("${PROJECT_NAME}" PRIVATE "${LIBSSH2_INCLUDE_DIR}")