Skip to content

Instantly share code, notes, and snippets.

@AlexsJones
Last active February 16, 2024 10:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save AlexsJones/0a574d32a0541a384f81 to your computer and use it in GitHub Desktop.
Save AlexsJones/0a574d32a0541a384f81 to your computer and use it in GitHub Desktop.
CMake Unity build example
cmake_minimum_required(VERSION 2.8)
set(CMAKE_INSTALL_PREFIX /usr)
project(UNITY_BUILD_NAME)
function(enable_unity_build UB_SUFFIX SOURCE_VARIABLE_NAME)
set(files ${${SOURCE_VARIABLE_NAME}})
# Generate a unique filename for the unity build translation unit
set(unit_build_file ${CMAKE_CURRENT_BINARY_DIR}/ub_${UB_SUFFIX}.cpp)
# Exclude all translation units from compilation
set_source_files_properties(${files} PROPERTIES HEADER_FILE_ONLY true)
# Open the ub file
FILE(WRITE ${unit_build_file} "// Unity Build generated by CMake\n")
# Add include statement for each translation unit
foreach(source_file ${files} )
FILE( APPEND ${unit_build_file} "#include <${CMAKE_CURRENT_SOURCE_DIR}/${source_file}>\n")
endforeach(source_file)
# Complement list of translation units with the name of ub
set(${SOURCE_VARIABLE_NAME} ${${SOURCE_VARIABLE_NAME}} ${unit_build_file} PARENT_SCOPE)
endfunction(enable_unity_build)
file(GLOB SRC "src/*.cpp")
file(GLOB INC "src/*.hpp")
enable_unity_build(UNITY_BUILD_NAME ${SRC})
add_executable(UNITY_BUILD_NAME ${INC} ${SRC})
@yhyu13
Copy link

yhyu13 commented Feb 16, 2024

This would work if you change to enable_unity_build(UNITY_BUILD_NAME SRC), but then I cannot debug with symbol automatically

switch to cmake unity build can replace this method

function(function_unity_build TARGET SOURCE_VARIABLE_NAME)
    set_target_properties(${TARGET} PROPERTIES UNITY_BUILD ON)
endfunction()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment