Using pre-compiled headers with CMake

后端 未结 14 2186
刺人心
刺人心 2020-12-12 10:39

I have seen a few (old) posts on the \'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has the

14条回答
  •  渐次进展
    2020-12-12 11:23

    Im using the following macro to generate and use precompiled headers:

    MACRO(ADD_MSVC_PRECOMPILED_HEADER PrecompiledHeader PrecompiledSource SourcesVar)
      IF(MSVC)
        GET_FILENAME_COMPONENT(PrecompiledBasename ${PrecompiledHeader} NAME_WE)
        SET(PrecompiledBinary "${CMAKE_CURRENT_BINARY_DIR}/${PrecompiledBasename}.pch")
        SET(Sources ${${SourcesVar}})
    
        SET_SOURCE_FILES_PROPERTIES(${PrecompiledSource}
                                    PROPERTIES COMPILE_FLAGS "/Yc\"${PrecompiledHeader}\" /Fp\"${PrecompiledBinary}\""
                                               OBJECT_OUTPUTS "${PrecompiledBinary}")
        SET_SOURCE_FILES_PROPERTIES(${Sources}
                                    PROPERTIES COMPILE_FLAGS "/Yu\"${PrecompiledHeader}\" /FI\"${PrecompiledHeader}\" /Fp\"${PrecompiledBinary}\""
                                               OBJECT_DEPENDS "${PrecompiledBinary}")  
        # Add precompiled header to SourcesVar
        LIST(APPEND ${SourcesVar} ${PrecompiledSource})
      ENDIF(MSVC)
    ENDMACRO(ADD_MSVC_PRECOMPILED_HEADER)
    

    Lets say you have a variable ${MySources} with all your sourcefiles, the code you would want to use would be simply be

    ADD_MSVC_PRECOMPILED_HEADER("precompiled.h" "precompiled.cpp" MySources)
    ADD_LIBRARY(MyLibrary ${MySources})
    

    The code would still function just fine on non-MSVC platforms too. Pretty neat :)

提交回复
热议问题