如何从CMake项目中的vcpkg正确链接库

时间:2019-03-21 08:35:50

标签: cmake vcpkg

我正在使用CMake项目测试vcpkg(在macOS上)。

由于并非所有vcpkg软件包都具有CMake查找模块,所以我正在尝试一个不包含以下模块的软件包:libuuid

这是相对于libuuid的目录树,我可以从vcpkg根目录中看到:

$ find packages/libuuid_x64-osx
packages/libuuid_x64-osx
packages/libuuid_x64-osx/include
packages/libuuid_x64-osx/include/uuid
packages/libuuid_x64-osx/include/uuid/uuid.h
packages/libuuid_x64-osx/BUILD_INFO
packages/libuuid_x64-osx/lib
packages/libuuid_x64-osx/lib/libuuid.a
packages/libuuid_x64-osx/CONTROL
packages/libuuid_x64-osx/debug
packages/libuuid_x64-osx/debug/lib
packages/libuuid_x64-osx/debug/lib/libuuid.a
packages/libuuid_x64-osx/share
packages/libuuid_x64-osx/share/libuuid
packages/libuuid_x64-osx/share/libuuid/copyright

示例程序:

#include <iostream>
#include <uuid/uuid.h>

int main(int argc, char **argv)
{
    std::cout << "Hello, world!" << std::endl;

    return 0;
}

示例CMakeLists.txt

cmake_minimum_required(VERSION 3.13)

project(vcpkg_example_project)

add_executable(app app.cpp)
target_link_libraries(app uuid)

如果我理解正确,vcpkg的理念不是提供缺少的CMake查找模块,而只是开箱即用#include <libfoo/foo.h>。实际上,以上示例可以很好地编译。但是找不到-luuid

$ cmake -DCMAKE_TOOCHAIN_FILE=/Users/me/Dev/vcpkg/scripts/buildsystems/vcpkg.cmake ..
...
$ cmake --build .
Scanning dependencies of target app
[ 50%] Building CXX object CMakeFiles/app.dir/app.cpp.o
[100%] Linking CXX executable app
ld: library not found for -luuid
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [app] Error 1
make[1]: *** [CMakeFiles/app.dir/all] Error 2
make: *** [all] Error 2

我想念什么?

此外,我看到有一个installed/x64-osx/lib/libuuid.ainstalled/x64-osx/lib是否应该由工具链cmake脚本自动添加为lib路径?

1 个答案:

答案 0 :(得分:0)

我会用uuid作为目标。根据您的描述,很可能是Interface Library,称为uuid。您可以add_target_include_directoriestarget_link_libraries来获取标题和任何库,然后将其添加到项目的其余部分。

是这样的:

add_library(uuid INTERFACE)

if(${CMAKE_BUILD_TYPE} strequal "Release")
    find_library(LIBUUID uuid "${CMAKE_CURRENT_SOURCE_DIR}/packages/libuuid_x64-osx/lib/")
else()
    find_library(LIBUUID uuid "${CMAKE_CURRENT_SOURCE_DIR}/packages/libuuid_x64-osx/debug/lib/")
endif()

target_link_libraries(uuid INTERFACE "${LIBUUID}")

target_include_directories(uuid SYSTEM INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/packages/libuuid_x64-osx/include")

然后我要对图书馆的文件夹进行add_subdirectory并链接到uuid