为非 CMake 模块创建目标

Creating a target for a non-CMake module

我是 CMake 的新手,正在尝试了解现代 CMake。

我正在 ubuntu 上使用 poppler-cpp 库创建一个项目。 这些库是使用 sudo apt install libpoppler-cpp-dev 安装的,因此它们都应该在系统路径上可用。

我的目标是最终让这个构建在多个平台上运行。但是婴儿步骤...

之前我使用 pkg-config

设置导入库如下
find_package(PkgConfig REQUIRED)
pkg_check_modules(POPPLER_CPP REQUIRED poppler-cpp)

target_link_libraries(${PROJECT_NAME} 
    # prefer to statically link poppler
    # the other option would be POPPLER_LIBRARIES
    PRIVATE ${POPPLER_CPP_STATIC_LIBRARIES}
)

target_include_directories(${PROJECT_NAME} 
    PUBLIC ${PROJECT_SOURCE_DIR}/include
    # Include output from pkg_config
    PUBLIC ${POPPLER_CPP_INCLUDE_DIRS}
    # Need to add this to use 
    # generated export headers
    ${PROJECT_BINARY_DIR}
)

target_compile_options(${PROJECT_NAME} 
    PUBLIC ${POPPLER_CPP_CFLAGS_OTHER})

在阅读了更多有关现代 CMake 的信息后,我决定改为将其设为目标。 所以我创建了一个 FindPopplerCpp.cmake 并添加了以下

find_package(PkgConfig REQUIRED)
pkg_check_modules(PC_POPPLER_CPP REQUIRED poppler-cpp)


set(PopplerCpp_VERSION ${PC_POPPLER_CPP_VERSION})
set(PopplerCpp_INCLUDE_DIRS ${PC_POPPLER_CPP_INCLUDE_DIRS})
set(PopplerCpp_CFLAGS_OTHER ${PC_POPPLER_CPP_CFLAGS_OTHER})


if(PC_POPPLER_CPP_FOUND AND NOT TARGET poppler::Cpp)
  add_library(poppler::Cpp INTERFACE IMPORTED)
  set_target_properties(poppler::Cpp PROPERTIES
        IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
        INTERFACE_INCLUDE_DIRECTORIES "${PC_POPPLER_CPP_INCLUDE_DIRS}"
        INTERFACE_LINK_LIBRARIES "${PC_POPPLER_CPP_STATIC_LIBRARIES}"
        INTERFACE_COMPILE_OPTIONS "${PC_POPPLER_CPP_CFLAGS}"
        VERSION "${PC_POPPLER_CPP_VERSION}"
    )
ELSE (PC_POPPLER_CPP_FOUND)
    MESSAGE(FATAL_ERROR "Could not find library")
endif()

mark_as_advanced(PopplerCpp_FOUND PopplerCpp_INCLUDE_DIRS PopplerCpp_VERSION)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PopplerCpp
    REQUIRED_VARS PopplerCpp_INCLUDE_DIRS
    VERSION_VAR PopplerCpp_VERSION
)

然后我导入目标

target_link_libraries(${PROJECT_NAME} 
    PRIVATE poppler::Cpp
)

我的理解是,这将处理所有链接器并包含路径。 我能够很好地构建目标并且它似乎工作正常。

静态库的使用是有意的。我将 poppler-cpp 库静态链接到我的共享库。

我只是想确保我设置正确,特别是考虑到我想在 mac 和 windows 上构建这个项目。我知道 pkg-config 在这里不起作用。但我到那儿后会过那座桥。

感谢您的帮助

您应该只使用 pkg_check_modulesIMPORTED_TARGET 选项...

find_package(PkgConfig REQUIRED)
pkg_check_modules(poppler-cpp REQUIRED IMPORTED_TARGET poppler-cpp)

target_link_libraries(my_target PRIVATE PkgConfig::poppler-cpp)