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

5us2dqdw  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(257)

我正在使用CMake项目测试vcpkg(在macOS上)。
由于并非所有的vcpkg包都有CMake find模块,我尝试使用一个没有CMake find模块的包:液体
这是相对于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 find-modules,而是简单地让#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路径吗?

5kgi1eie

5kgi1eie1#

我会用uuid做一个target。从你的描述来看,最有可能的是一个名为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

相关问题