cmakevcpkgcmake-gui

How to link a library installed by vcpkg using CMake?


I installed a third party library using vcpkg. If I write full path to library in include_directories and etc. commands it works but this is silly. I'm trying to include this library using proper approach but CMake returns an error.

I tried advices from similar questions but thus far I was unable to solve the problem

This is my CMakeLists.txt

SET(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake")

project(ESMTOOLKIT)

cmake_minimum_required(VERSION 3.15.5)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ../bin)

find_package(LibXml2 REQUIRED)

#include_directories(C:/Users/user/source/vcpkg/vcpkg/installed/x64-windows/include include)
include_directories(${LIBXML2_INCLUDE_DIRS} include)
#link_directories(C:/Users/user/source/vcpkg/vcpkg/installed/x64-windows/lib)

set(SOURCES xmlUtils.cpp include/xmlUtils.h pch.cpp include/pch.h esmReader.cpp)

add_executable(esmToolkit ${SOURCES})

#target_link_libraries(esmToolkit libxml2.lib)
target_link_libraries(esmToolkit PRIVATE ${LIBXML2_LIBRARIES})

add_subdirectory(subrecords)
add_subdirectory(records)

This is the error message that I get:

Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19044.
CMake Error at C:/Program Files/CMake/3_24/share/cmake-3.24/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
  Could NOT find LibXml2 (missing: LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
Call Stack (most recent call first):
  C:/Program Files/CMake/3_24/share/cmake-3.24/Modules/FindPackageHandleStandardArgs.cmake:594 (_FPHSA_FAILURE_MESSAGE)
  C:/Program Files/CMake/3_24/share/cmake-3.24/Modules/FindLibXml2.cmake:108 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:9 (find_package)


Configuring incomplete, errors occurred!
See also "C:/Users/user/source/repos/esmToolkit/build/CMakeFiles/CMakeOutput.log".

I have the following environmental variables set:

VCPKG_DEFAULT_TRIPLET x64-windows
VCPKG_ROOT C:\Users\user\source\vcpkg\vcpkg

What am I doing wrong?


Solution

  • Okay, I fixed an issue though I'm not sure what in particular fixed it.

    First, I found that I have path to CMake missing from Path environmental variable (C:\Program Files\CMake\3_24\bin).

    Second, I removed link_directories command and replaced include_directories command with a target_include_directories.

    Third, I changed how I use target_link_libraries command. The correct way for my case is the following: target_link_libraries(esmToolkit PRIVATE LibXml2::LibXml2)

    Now CMake generates correct solution from both command line and CMake-GUI