Using pre-compiled headers with CMake

后端 未结 14 2156
刺人心
刺人心 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 10:59

    IMHO the best way is to set PCH for whole project, as martjno suggested, combined with ability of ignoring PCH for some sources if needed (e.g. generated sources):

    # set PCH for VS project
    function(SET_TARGET_PRECOMPILED_HEADER Target PrecompiledHeader PrecompiledSource)
      if(MSVC)
         SET_TARGET_PROPERTIES(${Target} PROPERTIES COMPILE_FLAGS "/Yu${PrecompiledHeader}")
         set_source_files_properties(${PrecompiledSource} PROPERTIES COMPILE_FLAGS "/Yc${PrecompiledHeader}")
      endif(MSVC)
    endfunction(SET_TARGET_PRECOMPILED_HEADER)
    
    # ignore PCH for a specified list of files
    function(IGNORE_PRECOMPILED_HEADER SourcesVar)
      if(MSVC)  
        set_source_files_properties(${${SourcesVar}} PROPERTIES COMPILE_FLAGS "/Y-")
      endif(MSVC)
    endfunction(IGNORE_PRECOMPILED_HEADER)
    

    So, if you have some target MY_TARGET, and list of generated sources IGNORE_PCH_SRC_LIST you'll simply do:

    SET_TARGET_PRECOMPILED_HEADER(MY_TARGET stdafx.h stdafx.cpp)
    IGNORE_PRECOMPILED_HEADER(IGNORE_PCH_SRC_LIST)
    

    This aproach is tested and works perfectly.

提交回复
热议问题