WriteCompilerDetectionHeader.cmake 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #.rst:
  2. # WriteCompilerDetectionHeader
  3. # ----------------------------
  4. #
  5. # This module provides the function write_compiler_detection_header().
  6. #
  7. # The ``WRITE_COMPILER_DETECTION_HEADER`` function can be used to generate
  8. # a file suitable for preprocessor inclusion which contains macros to be
  9. # used in source code::
  10. #
  11. # write_compiler_detection_header(
  12. # FILE <file>
  13. # PREFIX <prefix>
  14. # COMPILERS <compiler> [...]
  15. # FEATURES <feature> [...]
  16. # [VERSION <version>]
  17. # [PROLOG <prolog>]
  18. # [EPILOG <epilog>]
  19. # )
  20. #
  21. # The ``write_compiler_detection_header`` function generates the
  22. # file ``<file>`` with macros which all have the prefix ``<prefix>``.
  23. #
  24. # ``VERSION`` may be used to specify the API version to be generated.
  25. # Future versions of CMake may introduce alternative APIs. A given
  26. # API is selected by any ``<version>`` value greater than or equal
  27. # to the version of CMake that introduced the given API and less
  28. # than the version of CMake that introduced its succeeding API.
  29. # The value of the :variable:`CMAKE_MINIMUM_REQUIRED_VERSION`
  30. # variable is used if no explicit version is specified.
  31. # (As of CMake version |release| there is only one API version.)
  32. #
  33. # ``PROLOG`` may be specified as text content to write at the start of the
  34. # header. ``EPILOG`` may be specified as text content to write at the end
  35. # of the header
  36. #
  37. # At least one ``<compiler>`` and one ``<feature>`` must be listed. Compilers
  38. # which are known to CMake, but not specified are detected and a preprocessor
  39. # ``#error`` is generated for them. A preprocessor macro matching
  40. # ``<PREFIX>_COMPILER_IS_<compiler>`` is generated for each compiler
  41. # known to CMake to contain the value ``0`` or ``1``.
  42. #
  43. # Possible compiler identifiers are documented with the
  44. # :variable:`CMAKE_<LANG>_COMPILER_ID` variable.
  45. # Available features in this version of CMake are listed in the
  46. # :prop_gbl:`CMAKE_C_KNOWN_FEATURES` and
  47. # :prop_gbl:`CMAKE_CXX_KNOWN_FEATURES` global properties.
  48. #
  49. # See the :manual:`cmake-compile-features(7)` manual for information on
  50. # compile features.
  51. #
  52. # Feature Test Macros
  53. # ===================
  54. #
  55. # For each compiler, a preprocessor test of the compiler version is generated
  56. # denoting whether each feature is enabled. A preprocessor macro
  57. # matching ``<PREFIX>_COMPILER_<FEATURE>``, where ``<FEATURE>`` is the
  58. # upper-case ``<feature>`` name, is generated to contain the value
  59. # ``0`` or ``1`` depending on whether the compiler in use supports the
  60. # feature:
  61. #
  62. # .. code-block:: cmake
  63. #
  64. # write_compiler_detection_header(
  65. # FILE climbingstats_compiler_detection.h
  66. # PREFIX ClimbingStats
  67. # COMPILERS GNU Clang MSVC
  68. # FEATURES cxx_variadic_templates
  69. # )
  70. #
  71. # .. code-block:: c++
  72. #
  73. # #if ClimbingStats_COMPILER_CXX_VARIADIC_TEMPLATES
  74. # template<typename... T>
  75. # void someInterface(T t...) { /* ... */ }
  76. # #else
  77. # // Compatibility versions
  78. # template<typename T1>
  79. # void someInterface(T1 t1) { /* ... */ }
  80. # template<typename T1, typename T2>
  81. # void someInterface(T1 t1, T2 t2) { /* ... */ }
  82. # template<typename T1, typename T2, typename T3>
  83. # void someInterface(T1 t1, T2 t2, T3 t3) { /* ... */ }
  84. # #endif
  85. #
  86. # Symbol Macros
  87. # =============
  88. #
  89. # Some additional symbol-defines are created for particular features for
  90. # use as symbols which may be conditionally defined empty:
  91. #
  92. # .. code-block:: c++
  93. #
  94. # class MyClass ClimbingStats_DECL_CXX_FINAL
  95. # {
  96. # ClimbingStats_DECL_CXX_CONSTEXPR int someInterface() { return 42; }
  97. # };
  98. #
  99. # The ``ClimbingStats_DECL_CXX_FINAL`` macro will expand to ``final`` if the
  100. # compiler (and its flags) support the ``cxx_final`` feature, and the
  101. # ``ClimbingStats_DECL_CXX_CONSTEXPR`` macro will expand to ``constexpr``
  102. # if ``cxx_constexpr`` is supported.
  103. #
  104. # The following features generate corresponding symbol defines:
  105. #
  106. # ========================== =================================== =================
  107. # Feature Define Symbol
  108. # ========================== =================================== =================
  109. # ``c_restrict`` ``<PREFIX>_RESTRICT`` ``restrict``
  110. # ``cxx_constexpr`` ``<PREFIX>_CONSTEXPR`` ``constexpr``
  111. # ``cxx_deleted_functions`` ``<PREFIX>_DELETED_FUNCTION`` ``= delete``
  112. # ``cxx_extern_templates`` ``<PREFIX>_EXTERN_TEMPLATE`` ``extern``
  113. # ``cxx_final`` ``<PREFIX>_FINAL`` ``final``
  114. # ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT`` ``noexcept``
  115. # ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT_EXPR(X)`` ``noexcept(X)``
  116. # ``cxx_override`` ``<PREFIX>_OVERRIDE`` ``override``
  117. # ========================== =================================== =================
  118. #
  119. # Compatibility Implementation Macros
  120. # ===================================
  121. #
  122. # Some features are suitable for wrapping in a macro with a backward
  123. # compatibility implementation if the compiler does not support the feature.
  124. #
  125. # When the ``cxx_static_assert`` feature is not provided by the compiler,
  126. # a compatibility implementation is available via the
  127. # ``<PREFIX>_STATIC_ASSERT(COND)`` and
  128. # ``<PREFIX>_STATIC_ASSERT_MSG(COND, MSG)`` function-like macros. The macros
  129. # expand to ``static_assert`` where that compiler feature is available, and
  130. # to a compatibility implementation otherwise. In the first form, the
  131. # condition is stringified in the message field of ``static_assert``. In
  132. # the second form, the message ``MSG`` is passed to the message field of
  133. # ``static_assert``, or ignored if using the backward compatibility
  134. # implementation.
  135. #
  136. # The ``cxx_attribute_deprecated`` feature provides a macro definition
  137. # ``<PREFIX>_DEPRECATED``, which expands to either the standard
  138. # ``[[deprecated]]`` attribute or a compiler-specific decorator such
  139. # as ``__attribute__((__deprecated__))`` used by GNU compilers.
  140. #
  141. # ============================= ================================ =====================
  142. # Feature Define Symbol
  143. # ============================= ================================ =====================
  144. # ``cxx_alignas`` ``<PREFIX>_ALIGNAS`` ``alignas``
  145. # ``cxx_alignof`` ``<PREFIX>_ALIGNOF`` ``alignof``
  146. # ``cxx_nullptr`` ``<PREFIX>_NULLPTR`` ``nullptr``
  147. # ``cxx_static_assert`` ``<PREFIX>_STATIC_ASSERT`` ``static_assert``
  148. # ``cxx_static_assert`` ``<PREFIX>_STATIC_ASSERT_MSG`` ``static_assert``
  149. # ``cxx_attribute_deprecated`` ``<PREFIX>_DEPRECATED`` ``[[deprecated]]``
  150. # ``cxx_attribute_deprecated`` ``<PREFIX>_DEPRECATED_MSG`` ``[[deprecated]]``
  151. # ============================= ================================ =====================
  152. #
  153. # A use-case which arises with such deprecation macros is the deprecation
  154. # of an entire library. In that case, all public API in the library may
  155. # be decorated with the ``<PREFIX>_DEPRECATED`` macro. This results in
  156. # very noisy build output when building the library itself, so the macro
  157. # may be may be defined to empty in that case when building the deprecated
  158. # library:
  159. #
  160. # .. code-block:: cmake
  161. #
  162. # add_library(compat_support ${srcs})
  163. # target_compile_definitions(compat_support
  164. # PRIVATE
  165. # CompatSupport_DEPRECATED=
  166. # )
  167. #=============================================================================
  168. # Copyright 2014 Stephen Kelly <[email protected]>
  169. #
  170. # Distributed under the OSI-approved BSD License (the "License");
  171. # see accompanying file Copyright.txt for details.
  172. #
  173. # This software is distributed WITHOUT ANY WARRANTY; without even the
  174. # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  175. # See the License for more information.
  176. #=============================================================================
  177. # (To distribute this file outside of CMake, substitute the full
  178. # License text for the above reference.)
  179. include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
  180. include(${CMAKE_CURRENT_LIST_DIR}/CMakeCompilerIdDetection.cmake)
  181. function(_load_compiler_variables CompilerId lang)
  182. include("${CMAKE_ROOT}/Modules/Compiler/${CompilerId}-${lang}-FeatureTests.cmake" OPTIONAL)
  183. set(_cmake_oldestSupported_${CompilerId} ${_cmake_oldestSupported} PARENT_SCOPE)
  184. foreach(feature ${ARGN})
  185. set(_cmake_feature_test_${CompilerId}_${feature} ${_cmake_feature_test_${feature}} PARENT_SCOPE)
  186. endforeach()
  187. endfunction()
  188. function(write_compiler_detection_header
  189. file_keyword file_arg
  190. prefix_keyword prefix_arg
  191. )
  192. if (NOT file_keyword STREQUAL FILE)
  193. message(FATAL_ERROR "write_compiler_detection_header: FILE parameter missing.")
  194. endif()
  195. if (NOT prefix_keyword STREQUAL PREFIX)
  196. message(FATAL_ERROR "write_compiler_detection_header: PREFIX parameter missing.")
  197. endif()
  198. set(options)
  199. set(oneValueArgs VERSION EPILOG PROLOG)
  200. set(multiValueArgs COMPILERS FEATURES)
  201. cmake_parse_arguments(_WCD "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  202. if (NOT _WCD_COMPILERS)
  203. message(FATAL_ERROR "Invalid arguments. write_compiler_detection_header requires at least one compiler.")
  204. endif()
  205. if (NOT _WCD_FEATURES)
  206. message(FATAL_ERROR "Invalid arguments. write_compiler_detection_header requires at least one feature.")
  207. endif()
  208. if(_WCD_UNPARSED_ARGUMENTS)
  209. message(FATAL_ERROR "Unparsed arguments: ${_WCD_UNPARSED_ARGUMENTS}")
  210. endif()
  211. if(NOT _WCD_VERSION)
  212. set(_WCD_VERSION ${CMAKE_MINIMUM_REQUIRED_VERSION})
  213. endif()
  214. if (_WCD_VERSION VERSION_LESS 3.1.0) # Version which introduced this function
  215. message(FATAL_ERROR "VERSION parameter too low.")
  216. endif()
  217. set(compilers
  218. GNU
  219. Clang
  220. )
  221. foreach(_comp ${_WCD_COMPILERS})
  222. list(FIND compilers ${_comp} idx)
  223. if (idx EQUAL -1)
  224. message(FATAL_ERROR "Unsupported compiler ${_comp}.")
  225. endif()
  226. endforeach()
  227. set(file_content "
  228. // This is a generated file. Do not edit!
  229. #ifndef ${prefix_arg}_COMPILER_DETECTION_H
  230. #define ${prefix_arg}_COMPILER_DETECTION_H
  231. ")
  232. if (_WCD_PROLOG)
  233. set(file_content "${file_content}\n${_WCD_PROLOG}\n")
  234. endif()
  235. foreach(feature ${_WCD_FEATURES})
  236. if (feature MATCHES "^cxx_")
  237. list(APPEND _langs CXX)
  238. list(APPEND CXX_features ${feature})
  239. elseif (feature MATCHES "^c_")
  240. list(APPEND _langs C)
  241. list(APPEND C_features ${feature})
  242. else()
  243. message(FATAL_ERROR "Unsupported feature ${feature}.")
  244. endif()
  245. endforeach()
  246. list(REMOVE_DUPLICATES _langs)
  247. foreach(_lang ${_langs})
  248. get_property(known_features GLOBAL PROPERTY CMAKE_${_lang}_KNOWN_FEATURES)
  249. foreach(feature ${${_lang}_features})
  250. list(FIND known_features ${feature} idx)
  251. if (idx EQUAL -1)
  252. message(FATAL_ERROR "Unsupported feature ${feature}.")
  253. endif()
  254. endforeach()
  255. if(_lang STREQUAL CXX)
  256. set(file_content "${file_content}\n#ifdef __cplusplus\n")
  257. else()
  258. set(file_content "${file_content}\n#ifndef __cplusplus\n")
  259. endif()
  260. compiler_id_detection(ID_CONTENT ${_lang} PREFIX ${prefix_arg}_
  261. ID_DEFINE
  262. )
  263. set(file_content "${file_content}${ID_CONTENT}\n")
  264. set(pp_if "if")
  265. foreach(compiler ${_WCD_COMPILERS})
  266. _load_compiler_variables(${compiler} ${_lang} ${${_lang}_features})
  267. set(file_content "${file_content}\n# ${pp_if} ${prefix_arg}_COMPILER_IS_${compiler}\n")
  268. set(file_content "${file_content}
  269. # if !(${_cmake_oldestSupported_${compiler}})
  270. # error Unsupported compiler version
  271. # endif\n")
  272. set(pp_if "elif")
  273. foreach(feature ${${_lang}_features})
  274. string(TOUPPER ${feature} feature_upper)
  275. set(feature_PP "COMPILER_${feature_upper}")
  276. set(_define_item "\n# define ${prefix_arg}_${feature_PP} 0\n")
  277. if (_cmake_feature_test_${compiler}_${feature} STREQUAL "1")
  278. set(_define_item "\n# define ${prefix_arg}_${feature_PP} 1\n")
  279. elseif (_cmake_feature_test_${compiler}_${feature})
  280. set(_define_item "\n# define ${prefix_arg}_${feature_PP} 0\n")
  281. set(_define_item "\n# if ${_cmake_feature_test_${compiler}_${feature}}\n# define ${prefix_arg}_${feature_PP} 1\n# else${_define_item}# endif\n")
  282. endif()
  283. set(file_content "${file_content}${_define_item}")
  284. endforeach()
  285. endforeach()
  286. if(pp_if STREQUAL "elif")
  287. set(file_content "${file_content}
  288. # else
  289. # error Unsupported compiler
  290. # endif\n")
  291. endif()
  292. foreach(feature ${${_lang}_features})
  293. string(TOUPPER ${feature} feature_upper)
  294. set(feature_PP "COMPILER_${feature_upper}")
  295. set(def_name ${prefix_arg}_${feature_PP})
  296. if (feature STREQUAL c_restrict)
  297. set(def_value "${prefix_arg}_RESTRICT")
  298. set(file_content "${file_content}
  299. # if ${def_name}
  300. # define ${def_value} restrict
  301. # else
  302. # define ${def_value}
  303. # endif
  304. \n")
  305. endif()
  306. if (feature STREQUAL cxx_constexpr)
  307. set(def_value "${prefix_arg}_DECL_${feature_upper}")
  308. set(file_content "${file_content}
  309. # if ${def_name}
  310. # define ${def_value} constexpr
  311. # else
  312. # define ${def_value}
  313. # endif
  314. \n")
  315. endif()
  316. if (feature STREQUAL cxx_final)
  317. set(def_value "${prefix_arg}_DECL_${feature_upper}")
  318. set(file_content "${file_content}
  319. # if ${def_name}
  320. # define ${def_value} final
  321. # else
  322. # define ${def_value}
  323. # endif
  324. \n")
  325. endif()
  326. if (feature STREQUAL cxx_override)
  327. set(def_value "${prefix_arg}_DECL_${feature_upper}")
  328. set(file_content "${file_content}
  329. # if ${def_name}
  330. # define ${def_value} override
  331. # else
  332. # define ${def_value}
  333. # endif
  334. \n")
  335. endif()
  336. if (feature STREQUAL cxx_static_assert)
  337. set(def_value "${prefix_arg}_STATIC_ASSERT(X)")
  338. set(def_value_msg "${prefix_arg}_STATIC_ASSERT_MSG(X, MSG)")
  339. set(static_assert_struct "template<bool> struct ${prefix_arg}StaticAssert;\ntemplate<> struct ${prefix_arg}StaticAssert<true>{};\n")
  340. set(def_standard "# define ${def_value} static_assert(X, #X)\n# define ${def_value_msg} static_assert(X, MSG)")
  341. set(def_alternative "${static_assert_struct}# define ${def_value} sizeof(${prefix_arg}StaticAssert<X>)\n# define ${def_value_msg} sizeof(${prefix_arg}StaticAssert<X>)")
  342. set(file_content "${file_content}# if ${def_name}\n${def_standard}\n# else\n${def_alternative}\n# endif\n\n")
  343. endif()
  344. if (feature STREQUAL cxx_alignas)
  345. set(def_value "${prefix_arg}_ALIGNAS(X)")
  346. set(file_content "${file_content}
  347. # if ${def_name}
  348. # define ${def_value} alignas(X)
  349. # elif ${prefix_arg}_COMPILER_IS_GNU
  350. # define ${def_value} __attribute__ ((__aligned__(X)))
  351. # else
  352. # define ${def_value}
  353. # endif
  354. \n")
  355. endif()
  356. if (feature STREQUAL cxx_alignof)
  357. set(def_value "${prefix_arg}_ALIGNOF(X)")
  358. set(file_content "${file_content}
  359. # if ${def_name}
  360. # define ${def_value} alignof(X)
  361. # elif ${prefix_arg}_COMPILER_IS_GNU
  362. # define ${def_value} __alignof__(X)
  363. # endif
  364. \n")
  365. endif()
  366. if (feature STREQUAL cxx_deleted_functions)
  367. set(def_value "${prefix_arg}_DELETED_FUNCTION")
  368. set(file_content "${file_content}
  369. # if ${def_name}
  370. # define ${def_value} = delete
  371. # else
  372. # define ${def_value}
  373. # endif
  374. \n")
  375. endif()
  376. if (feature STREQUAL cxx_extern_templates)
  377. set(def_value "${prefix_arg}_EXTERN_TEMPLATE")
  378. set(file_content "${file_content}
  379. # if ${def_name}
  380. # define ${def_value} extern
  381. # else
  382. # define ${def_value}
  383. # endif
  384. \n")
  385. endif()
  386. if (feature STREQUAL cxx_noexcept)
  387. set(def_value "${prefix_arg}_NOEXCEPT")
  388. set(file_content "${file_content}
  389. # if ${def_name}
  390. # define ${def_value} noexcept
  391. # define ${def_value}_EXPR(X) noexcept(X)
  392. # else
  393. # define ${def_value}
  394. # define ${def_value}_EXPR(X)
  395. # endif
  396. \n")
  397. endif()
  398. if (feature STREQUAL cxx_nullptr)
  399. set(def_value "${prefix_arg}_NULLPTR")
  400. set(file_content "${file_content}
  401. # if ${def_name}
  402. # define ${def_value} nullptr
  403. # else
  404. # define ${def_value} static_cast<void*>(0)
  405. # endif
  406. \n")
  407. endif()
  408. if (feature STREQUAL cxx_attribute_deprecated)
  409. set(def_name ${prefix_arg}_${feature_PP})
  410. set(def_value "${prefix_arg}_DEPRECATED")
  411. set(file_content "${file_content}
  412. # ifndef ${def_value}
  413. # if ${def_name}
  414. # define ${def_value} [[deprecated]]
  415. # define ${def_value}_MSG(MSG) [[deprecated(MSG)]]
  416. # elif defined(__GNUC__) || defined(__clang__)
  417. # define ${def_value} __attribute__((__deprecated__))
  418. # define ${def_value}_MSG(MSG) __attribute__((__deprecated__(MSG)))
  419. # elif defined(_MSC_VER)
  420. # define ${def_value} __declspec(deprecated)
  421. # define ${def_value}_MSG(MSG) __declspec(deprecated(MSG))
  422. # else
  423. # define ${def_value}
  424. # define ${def_value}_MSG(MSG)
  425. # endif
  426. # endif
  427. \n")
  428. endif()
  429. endforeach()
  430. set(file_content "${file_content}#endif\n")
  431. endforeach()
  432. if (_WCD_EPILOG)
  433. set(file_content "${file_content}\n${_WCD_EPILOG}\n")
  434. endif()
  435. set(file_content "${file_content}\n#endif")
  436. set(CMAKE_CONFIGURABLE_FILE_CONTENT ${file_content})
  437. configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
  438. "${file_arg}"
  439. @ONLY
  440. )
  441. endfunction()