UNITY BUILD加速cmake 编译

cmake_minimum_required(VERSION 3.10.0)

project(cmake_test VERSION 0.1.0 LANGUAGES C CXX)

set(CMAKE_VERBOSE_MAKEFILE ON)

set(include_dirs

    ${CMAKE_CURRENT_LIST_DIR}

    ${CMAKE_CURRENT_LIST_DIR}/minus

    ${CMAKE_CURRENT_LIST_DIR}/sum

)

set(precompile_headers

    ${CMAKE_CURRENT_LIST_DIR}/minus/minus.h

    ${CMAKE_CURRENT_LIST_DIR}/sum/sum.h

)

##############################定义功能lib#################################

add_library(alg-obj OBJECT ${CMAKE_CURRENT_LIST_DIR}/minus/minus.c ${CMAKE_CURRENT_LIST_DIR}/sum/sum.c)

target_include_directories(alg-obj PRIVATE ${include_dirs})

add_library(my_math-obj OBJECT ${CMAKE_CURRENT_LIST_DIR}/my_math.cpp)

target_include_directories(my_math-obj PRIVATE ${include_dirs})

list(APPEND all_link_libs

alg-obj

my_math-obj)

list(APPEND unity_build_libs alg-obj my_math-obj)

# message(all_link_libs:${all_link_libs})

# list(REMOVE_ITEM all_link_libs ${unity_build_libs})

# list(APPEND all_link_libs com_lib)

# message(all_link_libs----:${all_link_libs})

##############################使用UNITY_BUILD加速编译#################################

macro(add_unity_build_lib target unity_build_libs)

    # UNITY_BUILD:将多个(UNITY_BUILD_BATCH_SIZE)源文件合并为1个源文件编译,提高编译效率

    # 1. 获取所有源文件

    foreach(lib ${unity_build_libs})

        get_target_property(TARGET_SOURCES ${lib} SOURCES)

        list(APPEND unity_build_src ${TARGET_SOURCES})

    endforeach()

    # 2. 添加新的lib

    add_library(${target} OBJECT ${unity_build_src})

    target_include_directories(${target} PRIVATE ${include_dirs})

    target_precompile_headers(${target} PUBLIC ${precompile_headers}) # 定义预编译头文件,只对该obj有效和依赖该obj的obj有效

    set_target_properties(${target} PROPERTIES UNITY_BUILD ON) # 启用UNITY_BUILD,只对该obj的源文件生效

    # 3. 替换为新的lib

    message(all_link_libs:${all_link_libs})

    list(REMOVE_ITEM all_link_libs ${unity_build_libs})

    list(APPEND all_link_libs ${target})

    message(all_link_libs:${all_link_libs})

endmacro()

add_unity_build_lib(comm_lib ${unity_build_libs})

#########################可执行文件#################################

message(all_link_libs:${all_link_libs})

add_executable(cmake_test ${CMAKE_CURRENT_LIST_DIR}/main.cpp)

target_include_directories(cmake_test PRIVATE ${include_dirs})

target_link_libraries(cmake_test PRIVATE ${all_link_libs})