cmake:将 header-only 库编译成 STATIC 库

cmake: compile header-only library into a STATIC library

我正在使用 VulkanMemoryAllocation,这是一个仅 header 的库。我想使用 cmake 将它编译成一个静态库,但我最终得到一个空的 - 8 字节大小的 - 库文件,并且在链接时有很多未定义的符号。

这是CMakeList.txt

的相关部分
# The header with the implementation
add_library(VulkanMemoryAllocator STATIC VulkanMemoryAllocator-Hpp/vk_mem_alloc.h)
# The include path for a wrapper which uses above mentionned header
target_include_directories(VulkanMemoryAllocator PUBLIC VulkanMemoryAllocator-Hpp/)
# enable the actual implementation
target_compile_options(VulkanMemoryAllocator PRIVATE VMA_IMPLEMENTATION)
# consider this file as a C++ file
set_target_properties(VulkanMemoryAllocator PROPERTIES LINKER_LANGUAGE CXX)

编辑:我想做类似的事情:

clang++ -c -DVMA_IMPLEMENTATION -x c++ -o vk_mem_alloc.o  ../lib/VulkanMemoryAllocator-Hpp/vk_mem_alloc.h && ar rc libvma.a vk_mem_alloc.o

但使用 CMake

VMA_IMPLEMENTATIONcompile_definition 而不是 compile_option

除了目标(我认为)之外,您还必须设置 文件 语言。

set_source_file_properties(
    VulkanMemoryAllocator-Hpp/vk_mem_alloc.h PROPERTIES
    LANGUAGE CXX
)

我只是复制 header 以便 CMake 从扩展中知道它是 C++,它更简单。

add_custom_command(
    COMMENT 'Copying vk_mem_alloc'
    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/vk_mem_alloc.cpp
    DEPENDS VulkanMemoryAllocator-Hpp/vk_mem_alloc.h
    COMMAND ${CMAKE_COMMAND} -E copy
        VulkanMemoryAllocator-Hpp/vk_mem_alloc.h
        ${CMAKE_CURRENT_BINARY_DIR}/vk_mem_alloc.cpp
)
add_library(VulkanMemoryAllocator STATIC
    ${CMAKE_CURRENT_BINARY_DIR}/vk_mem_alloc.cpp
)
target_include_directories(VulkanMemoryAllocator PUBLIC
    VulkanMemoryAllocator-Hpp
)
target_compile_definitions(VulkanMemoryAllocator PRIVATE
    VMA_IMPLEMENTATION
)

这里 https://github.com/usnistgov/hevx/blob/master/third_party/VulkanMemoryAllocator.cmake 是一个类似的解决方案,它使用 #define 创建一个 C++ 文件并编译它。