CMake Snippets | Blurred code

CMake Snippets

2023/07/28

LastMod:2023/07/30

Categories: CMake

笔记栏文章声明

Warning

笔记栏所记录文章往往未经校对,或包含错误认识或偏颇观点,亦或采用只有自身能够理解的记录。

跨平台创建类似于Symlink

take from cmake - replacement of create_symlink in windows - Stack Overflow

在Windows上有一个替代品 Directory Junction。 对于单机用户基本上没区别。 区别在于

see: https://superuser.com/a/343079

if(NOT EXISTS ${CMAKE_BINARY_DIR}/bin/media)
    if (UNIX)
        execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink ${CMAKE_SOURCE_DIR}/media ${CMAKE_BINARY_DIR}/bin/media)
    else()
        # also there is symlink/hardlink on windows, it requires admin permission
        file(TO_NATIVE_PATH "${CMAKE_BINARY_DIR}/bin/media" _dstDir)
        file(TO_NATIVE_PATH "${CMAKE_SOURCE_DIR}/media" _srcDir)
        execute_process(COMMAND cmd.exe /c mklink /J "${_dstDir}" "${_srcDir}")
    endif()
endif()

引入VCPKG ToolChain

避免每次都要cmake ../my/project -DCMAKE_TOOLCHAIN_FILE=<vcpkg-root>/scripts/buildsystems/vcpkg.cmake

新版本的CMake(>= 3.19)可以选择用CMakePresets.json或者CMakeUserPresets.json

用法:

include(${CMAKE_SOURCE_DIR}/cmake/utils.cmake)
set(vcpkg "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake")

if(NOT CMAKE_TOOLCHAIN_FILE AND EXISTS "${vcpkg}")
    set(CMAKE_TOOLCHAIN_FILE "${vcpkg}"
        CACHE FILEPATH "CMake toolchain file")
    message(STATUS "vcpkg toolchain found: ${CMAKE_TOOLCHAIN_FILE}")
endif()