CMakeLists.txt 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. cmake_minimum_required (VERSION 3.9)
  2. project(PrecompiledHeader C)
  3. # Make sure the proper compiler is in use.
  4. if(NOT MSVC AND NOT CMAKE_C_COMPILER_ID STREQUAL "Intel")
  5. message(FATAL_ERROR "The PrecompiledHeader test works only with MSVC or Intel")
  6. endif()
  7. # Compute a custom name for the precompiled header.
  8. get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
  9. if(_isMultiConfig)
  10. set(PCH_DIR "${CMAKE_CURRENT_BINARY_DIR}/PCH/${CMAKE_CFG_INTDIR}")
  11. foreach(cfg ${CMAKE_CONFIGURATION_TYPES})
  12. file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/PCH/${cfg})
  13. endforeach()
  14. else()
  15. set(PCH_DIR "${CMAKE_CURRENT_BINARY_DIR}/PCH")
  16. file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/PCH)
  17. endif()
  18. set(PCH_USE_INCLUDE_DIR 0)
  19. set(PCH_FILE "\"/Fp${PCH_DIR}/foo_precompiled.pch\"")
  20. # Choose between an explicit include path and using /I during
  21. # precompilation. The /I form is used to test that the PCH is
  22. # actually used. In practice the include path form would be used.
  23. if(PCH_USE_INCLUDE_DIR)
  24. include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
  25. else()
  26. set(PCH_INCLUDE_DIR "\"/I${CMAKE_CURRENT_SOURCE_DIR}/include\"")
  27. endif()
  28. # Create a target that will use a precompiled header.
  29. set(foo_SRCS foo1.c foo2.c)
  30. add_executable(foo foo_precompile.c ${foo_SRCS})
  31. # Setup flags on the target to create and use the precompiled header.
  32. set_target_properties(foo PROPERTIES
  33. COMPILE_FLAGS "/Yufoo_precompiled.h /FIfoo_precompiled.h ${PCH_FILE}")
  34. set_source_files_properties(foo_precompile.c PROPERTIES
  35. COMPILE_FLAGS "/Ycfoo_precompiled.h ${PCH_INCLUDE_DIR}")
  36. # Setup dependencies for precompiled header creation and use. The VS
  37. # IDE takes care of this automatically.
  38. if("${CMAKE_GENERATOR}" MATCHES "Makefile" OR
  39. "${CMAKE_GENERATOR}" MATCHES "Ninja")
  40. # This source file creates the precompiled header as a side-effect.
  41. set_source_files_properties(foo_precompile.c PROPERTIES
  42. OBJECT_OUTPUTS "${PCH_DIR}/foo_precompiled.pch")
  43. # These source files use the precompiled header.
  44. set_source_files_properties(${foo_SRCS} PROPERTIES
  45. OBJECT_DEPENDS "${PCH_DIR}/foo_precompiled.pch")
  46. endif()