CMake跨平台库链接

时间:2020-07-14 18:34:18

标签: c++ cmake

我有一个使用大量外部库的项目。我使用CMake作为构建系统。目前,我添加并链接到这样的库:

##### LIBRARIES ###############################################

# Try to find the library the "classic" way
find_library("DEPENDENCY_GLFW" NAMES "glfw" "glfw3")

# Try to find a package for the library
find_package(glfw3 CONFIG)

# Check if the library has been found using the "classic" way
if(DEPENDENCY_GLFW MATCHES "NOTFOUND")
    # If it was not found, check if find_package found it
    if(glfw3_FOUND)
        # find_package found it, add target 
        list(APPEND "DEPENDENCIES" "glfw")
        message(STATUS ">> Found dependency: GLEW")
    else()
        # Has not been found
        message(WARNING ">> Unable to find dependency: GLFW")
    endif()
else()
    # Found it with the "classic" way
    list(APPEND "DEPENDENCIES" "${DEPENDENCY_GLFW}")
    message(STATUS ">> Found dependency: GLFW")
endif()

##### HEADERS #################################################

# Find the header path
find_path(GLFW_INCLUDE_DIRECTORY "GLFW/glfw3.h")
if(GLFW_INCLUDE_DIRECTORY MATCHES "NOTFOUND")
    # Has not been found
    message(WARNING ">> Unable to find dependency headers: GLFW")
else()
    # Has been found, add directory to list
    list(APPEND "DEPENDENCIES_HEADERS" "${GLFW_INCLUDE_DIRECTORY}")
    message(STATUS ">> Found dependency headers: GLFW")
endif()

# ...

target_include_directories("mytarget" PUBLIC "${DEPENDENCIES_HEADERS}")
target_link_libraries("mytarget" PUBLIC "${DEPENDENCIES}")

尽管这可行,但我很确定有更好的方法来完成此操作。 该代码应尽可能地跨平台,这意味着您应该能够链接到vcpkg提供的CMake软件包(例如,在Windows上)或仅链接到库(例如,在Linux上)。

0 个答案:

没有答案