dorfen_
dorfen_

Reputation: 85

cmake: compile header-only library into a STATIC library

I'm using VulkanMemoryAllocation, which is a header only library. I want to compile it into a static library using cmake, but I end up with an empty - 8 bytes sized - library file, and a lot of undefined symbols when linking.

Here is the relevant part of the 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)

EDIT : I want to do the equivalent of this :

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

but using CMake

Upvotes: 2

Views: 988

Answers (1)

KamilCuk
KamilCuk

Reputation: 141020

VMA_IMPLEMENTATION is a compile_definition not compile_option.

You have to set file language, in addition to target (I think).

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

I would just copy the header so that CMake knows it's C++ from extension, it's just simpler.

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
)

Here https://github.com/usnistgov/hevx/blob/master/third_party/VulkanMemoryAllocator.cmake is a similar solution, that creates a C++ file with #define and compiles it.

Upvotes: 2

Related Questions