WriteCompilerDetectionHeader.cmake 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file LICENSE.rst or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. WriteCompilerDetectionHeader
  5. ----------------------------
  6. .. deprecated:: 3.20
  7. This module is available only if policy :policy:`CMP0120`
  8. is not set to ``NEW``. Do not use it in new code.
  9. .. versionadded:: 3.1
  10. This module provides a command to generate header with preprocessor macros.
  11. Load this module in a CMake project with:
  12. .. code-block:: cmake
  13. include(WriteCompilerDetectionHeader)
  14. Commands
  15. ^^^^^^^^
  16. This module provides the following command:
  17. .. command:: write_compiler_detection_header
  18. This function can be used to generate a file suitable for preprocessor
  19. inclusion which contains macros to be used in source code:
  20. .. code-block:: cmake
  21. write_compiler_detection_header(
  22. FILE <file>
  23. PREFIX <prefix>
  24. [OUTPUT_FILES_VAR <output_files_var> OUTPUT_DIR <output_dir>]
  25. COMPILERS <compiler> [...]
  26. FEATURES <feature> [...]
  27. [BARE_FEATURES <feature> [...]]
  28. [VERSION <version>]
  29. [PROLOG <prolog>]
  30. [EPILOG <epilog>]
  31. [ALLOW_UNKNOWN_COMPILERS]
  32. [ALLOW_UNKNOWN_COMPILER_VERSIONS]
  33. )
  34. This generates the file ``<file>`` with macros which all have the prefix
  35. ``<prefix>``.
  36. By default, all content is written directly to the ``<file>``. The
  37. ``OUTPUT_FILES_VAR`` may be specified to cause the compiler-specific
  38. content to be written to separate files. The separate files are then
  39. available in the ``<output_files_var>`` and may be consumed by the caller
  40. for installation for example. The ``OUTPUT_DIR`` specifies a relative
  41. path from the main ``<file>`` to the compiler-specific files. For example:
  42. .. code-block:: cmake
  43. write_compiler_detection_header(
  44. FILE climbingstats_compiler_detection.h
  45. PREFIX ClimbingStats
  46. OUTPUT_FILES_VAR support_files
  47. OUTPUT_DIR compilers
  48. COMPILERS GNU Clang MSVC Intel
  49. FEATURES cxx_variadic_templates
  50. )
  51. install(FILES
  52. ${CMAKE_CURRENT_BINARY_DIR}/climbingstats_compiler_detection.h
  53. DESTINATION include
  54. )
  55. install(FILES
  56. ${support_files}
  57. DESTINATION include/compilers
  58. )
  59. ``VERSION`` may be used to specify the API version to be generated.
  60. Future versions of CMake may introduce alternative APIs. A given
  61. API is selected by any ``<version>`` value greater than or equal
  62. to the version of CMake that introduced the given API and less
  63. than the version of CMake that introduced its succeeding API.
  64. The value of the :variable:`CMAKE_MINIMUM_REQUIRED_VERSION`
  65. variable is used if no explicit version is specified.
  66. (As of CMake version |release| there is only one API version.)
  67. ``PROLOG`` may be specified as text content to write at the start of the
  68. header. ``EPILOG`` may be specified as text content to write at the end
  69. of the header
  70. At least one ``<compiler>`` and one ``<feature>`` must be listed. Compilers
  71. which are known to CMake, but not specified are detected and a preprocessor
  72. ``#error`` is generated for them. A preprocessor macro matching
  73. ``<PREFIX>_COMPILER_IS_<compiler>`` is generated for each compiler
  74. known to CMake to contain the value ``0`` or ``1``.
  75. Possible compiler identifiers are documented with the
  76. :variable:`CMAKE_<LANG>_COMPILER_ID` variable.
  77. Available features in this version of CMake are listed in the
  78. :prop_gbl:`CMAKE_C_KNOWN_FEATURES` and
  79. :prop_gbl:`CMAKE_CXX_KNOWN_FEATURES` global properties.
  80. See the :manual:`cmake-compile-features(7)` manual for information on
  81. compile features.
  82. .. versionadded:: 3.2
  83. Added ``MSVC`` and ``AppleClang`` compiler support.
  84. .. versionadded:: 3.6
  85. Added ``Intel`` compiler support.
  86. .. versionchanged:: 3.8
  87. The ``{c,cxx}_std_*`` meta-features are ignored if requested.
  88. .. versionadded:: 3.8
  89. ``ALLOW_UNKNOWN_COMPILERS`` and ``ALLOW_UNKNOWN_COMPILER_VERSIONS`` cause
  90. the module to generate conditions that treat unknown compilers as simply
  91. lacking all features. Without these options the default behavior is to
  92. generate a ``#error`` for unknown compilers and versions.
  93. .. versionadded:: 3.12
  94. ``BARE_FEATURES`` will define the compatibility macros with the name used in
  95. newer versions of the language standard, so the code can use the new feature
  96. name unconditionally.
  97. Feature Test Macros
  98. ===================
  99. For each compiler, a preprocessor macro is generated matching
  100. ``<PREFIX>_COMPILER_IS_<compiler>`` which has the content either ``0``
  101. or ``1``, depending on the compiler in use. Preprocessor macros for
  102. compiler version components are generated matching
  103. ``<PREFIX>_COMPILER_VERSION_MAJOR`` ``<PREFIX>_COMPILER_VERSION_MINOR``
  104. and ``<PREFIX>_COMPILER_VERSION_PATCH`` containing decimal values
  105. for the corresponding compiler version components, if defined.
  106. A preprocessor test is generated based on the compiler version
  107. denoting whether each feature is enabled. A preprocessor macro
  108. matching ``<PREFIX>_COMPILER_<FEATURE>``, where ``<FEATURE>`` is the
  109. upper-case ``<feature>`` name, is generated to contain the value
  110. ``0`` or ``1`` depending on whether the compiler in use supports the
  111. feature:
  112. .. code-block:: cmake
  113. write_compiler_detection_header(
  114. FILE climbingstats_compiler_detection.h
  115. PREFIX ClimbingStats
  116. COMPILERS GNU Clang AppleClang MSVC Intel
  117. FEATURES cxx_variadic_templates
  118. )
  119. .. code-block:: c++
  120. #if ClimbingStats_COMPILER_CXX_VARIADIC_TEMPLATES
  121. template<typename... T>
  122. void someInterface(T t...) { /* ... */ }
  123. #else
  124. // Compatibility versions
  125. template<typename T1>
  126. void someInterface(T1 t1) { /* ... */ }
  127. template<typename T1, typename T2>
  128. void someInterface(T1 t1, T2 t2) { /* ... */ }
  129. template<typename T1, typename T2, typename T3>
  130. void someInterface(T1 t1, T2 t2, T3 t3) { /* ... */ }
  131. #endif
  132. Symbol Macros
  133. =============
  134. Some additional symbol-defines are created for particular features for
  135. use as symbols which may be conditionally defined empty:
  136. .. code-block:: c++
  137. class MyClass ClimbingStats_FINAL
  138. {
  139. ClimbingStats_CONSTEXPR int someInterface() { return 42; }
  140. };
  141. The ``ClimbingStats_FINAL`` macro will expand to ``final`` if the
  142. compiler (and its flags) support the ``cxx_final`` feature, and the
  143. ``ClimbingStats_CONSTEXPR`` macro will expand to ``constexpr``
  144. if ``cxx_constexpr`` is supported.
  145. If ``BARE_FEATURES cxx_final`` was given as argument the ``final`` keyword
  146. will be defined for old compilers, too.
  147. The following features generate corresponding symbol defines and if they
  148. are available as ``BARE_FEATURES``:
  149. ========================== =================================== ================= ======
  150. Feature Define Symbol bare
  151. ========================== =================================== ================= ======
  152. ``c_restrict`` ``<PREFIX>_RESTRICT`` ``restrict`` yes
  153. ``cxx_constexpr`` ``<PREFIX>_CONSTEXPR`` ``constexpr`` yes
  154. ``cxx_deleted_functions`` ``<PREFIX>_DELETED_FUNCTION`` ``= delete``
  155. ``cxx_extern_templates`` ``<PREFIX>_EXTERN_TEMPLATE`` ``extern``
  156. ``cxx_final`` ``<PREFIX>_FINAL`` ``final`` yes
  157. ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT`` ``noexcept`` yes
  158. ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT_EXPR(X)`` ``noexcept(X)``
  159. ``cxx_override`` ``<PREFIX>_OVERRIDE`` ``override`` yes
  160. ========================== =================================== ================= ======
  161. Compatibility Implementation Macros
  162. ===================================
  163. Some features are suitable for wrapping in a macro with a backward
  164. compatibility implementation if the compiler does not support the feature.
  165. When the ``cxx_static_assert`` feature is not provided by the compiler,
  166. a compatibility implementation is available via the
  167. ``<PREFIX>_STATIC_ASSERT(COND)`` and
  168. ``<PREFIX>_STATIC_ASSERT_MSG(COND, MSG)`` function-like macros. The macros
  169. expand to ``static_assert`` where that compiler feature is available, and
  170. to a compatibility implementation otherwise. In the first form, the
  171. condition is stringified in the message field of ``static_assert``. In
  172. the second form, the message ``MSG`` is passed to the message field of
  173. ``static_assert``, or ignored if using the backward compatibility
  174. implementation.
  175. The ``cxx_attribute_deprecated`` feature provides a macro definition
  176. ``<PREFIX>_DEPRECATED``, which expands to either the standard
  177. ``[[deprecated]]`` attribute or a compiler-specific decorator such
  178. as ``__attribute__((__deprecated__))`` used by GNU compilers.
  179. The ``cxx_alignas`` feature provides a macro definition
  180. ``<PREFIX>_ALIGNAS`` which expands to either the standard ``alignas``
  181. decorator or a compiler-specific decorator such as
  182. ``__attribute__ ((__aligned__))`` used by GNU compilers.
  183. The ``cxx_alignof`` feature provides a macro definition
  184. ``<PREFIX>_ALIGNOF`` which expands to either the standard ``alignof``
  185. decorator or a compiler-specific decorator such as ``__alignof__``
  186. used by GNU compilers.
  187. ============================= ================================ ===================== ======
  188. Feature Define Symbol bare
  189. ============================= ================================ ===================== ======
  190. ``cxx_alignas`` ``<PREFIX>_ALIGNAS`` ``alignas``
  191. ``cxx_alignof`` ``<PREFIX>_ALIGNOF`` ``alignof``
  192. ``cxx_nullptr`` ``<PREFIX>_NULLPTR`` ``nullptr`` yes
  193. ``cxx_static_assert`` ``<PREFIX>_STATIC_ASSERT`` ``static_assert``
  194. ``cxx_static_assert`` ``<PREFIX>_STATIC_ASSERT_MSG`` ``static_assert``
  195. ``cxx_attribute_deprecated`` ``<PREFIX>_DEPRECATED`` ``[[deprecated]]``
  196. ``cxx_attribute_deprecated`` ``<PREFIX>_DEPRECATED_MSG`` ``[[deprecated]]``
  197. ``cxx_thread_local`` ``<PREFIX>_THREAD_LOCAL`` ``thread_local``
  198. ============================= ================================ ===================== ======
  199. A use-case which arises with such deprecation macros is the deprecation
  200. of an entire library. In that case, all public API in the library may
  201. be decorated with the ``<PREFIX>_DEPRECATED`` macro. This results in
  202. very noisy build output when building the library itself, so the macro
  203. may be may be defined to empty in that case when building the deprecated
  204. library:
  205. .. code-block:: cmake
  206. add_library(compat_support ${srcs})
  207. target_compile_definitions(compat_support
  208. PRIVATE
  209. CompatSupport_DEPRECATED=
  210. )
  211. .. _`WCDH Example Usage`:
  212. Example Usage
  213. =============
  214. .. note::
  215. This section was migrated from the :manual:`cmake-compile-features(7)`
  216. manual since it relies on the ``WriteCompilerDetectionHeader`` module
  217. which is removed by policy :policy:`CMP0120`.
  218. Compile features may be preferred if available, without creating a hard
  219. requirement. For example, a library may provide alternative
  220. implementations depending on whether the ``cxx_variadic_templates``
  221. feature is available:
  222. .. code-block:: c++
  223. #if Foo_COMPILER_CXX_VARIADIC_TEMPLATES
  224. template<int I, int... Is>
  225. struct Interface;
  226. template<int I>
  227. struct Interface<I>
  228. {
  229. static int accumulate()
  230. {
  231. return I;
  232. }
  233. };
  234. template<int I, int... Is>
  235. struct Interface
  236. {
  237. static int accumulate()
  238. {
  239. return I + Interface<Is...>::accumulate();
  240. }
  241. };
  242. #else
  243. template<int I1, int I2 = 0, int I3 = 0, int I4 = 0>
  244. struct Interface
  245. {
  246. static int accumulate() { return I1 + I2 + I3 + I4; }
  247. };
  248. #endif
  249. Such an interface depends on using the correct preprocessor defines for the
  250. compiler features. CMake can generate a header file containing such
  251. defines using the :module:`WriteCompilerDetectionHeader` module. The
  252. module contains the ``write_compiler_detection_header`` function which
  253. accepts parameters to control the content of the generated header file:
  254. .. code-block:: cmake
  255. write_compiler_detection_header(
  256. FILE "${CMAKE_CURRENT_BINARY_DIR}/foo_compiler_detection.h"
  257. PREFIX Foo
  258. COMPILERS GNU
  259. FEATURES
  260. cxx_variadic_templates
  261. )
  262. Such a header file may be used internally in the source code of a project,
  263. and it may be installed and used in the interface of library code.
  264. For each feature listed in ``FEATURES``, a preprocessor definition
  265. is created in the header file, and defined to either ``1`` or ``0``.
  266. Additionally, some features call for additional defines, such as the
  267. ``cxx_final`` and ``cxx_override`` features. Rather than being used in
  268. ``#ifdef`` code, the ``final`` keyword is abstracted by a symbol
  269. which is defined to either ``final``, a compiler-specific equivalent, or
  270. to empty. That way, C++ code can be written to unconditionally use the
  271. symbol, and compiler support determines what it is expanded to:
  272. .. code-block:: c++
  273. struct Interface {
  274. virtual void Execute() = 0;
  275. };
  276. struct Concrete Foo_FINAL {
  277. void Execute() Foo_OVERRIDE;
  278. };
  279. In this case, ``Foo_FINAL`` will expand to ``final`` if the
  280. compiler supports the keyword, or to empty otherwise.
  281. In this use-case, the project code may wish to enable a particular language
  282. standard if available from the compiler. The :prop_tgt:`CXX_STANDARD`
  283. target property may be set to the desired language standard for a particular
  284. target, and the :variable:`CMAKE_CXX_STANDARD` variable may be set to
  285. influence all following targets:
  286. .. code-block:: cmake
  287. write_compiler_detection_header(
  288. FILE "${CMAKE_CURRENT_BINARY_DIR}/foo_compiler_detection.h"
  289. PREFIX Foo
  290. COMPILERS GNU
  291. FEATURES
  292. cxx_final cxx_override
  293. )
  294. # Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
  295. # which will expand to 'final' if the compiler supports the requested
  296. # CXX_STANDARD.
  297. add_library(foo foo.cpp)
  298. set_property(TARGET foo PROPERTY CXX_STANDARD 11)
  299. # Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
  300. # which will expand to 'final' if the compiler supports the feature,
  301. # even though CXX_STANDARD is not set explicitly. The requirement of
  302. # cxx_constexpr causes CMake to set CXX_STANDARD internally, which
  303. # affects the compile flags.
  304. add_library(foo_impl foo_impl.cpp)
  305. target_compile_features(foo_impl PRIVATE cxx_constexpr)
  306. The ``write_compiler_detection_header`` function also creates compatibility
  307. code for other features which have standard equivalents. For example, the
  308. ``cxx_static_assert`` feature is emulated with a template and abstracted
  309. via the ``<PREFIX>_STATIC_ASSERT`` and ``<PREFIX>_STATIC_ASSERT_MSG``
  310. function-macros.
  311. #]=======================================================================]
  312. # Guard against inclusion by absolute path.
  313. cmake_policy(GET CMP0120 _WCDH_policy)
  314. if(_WCDH_policy STREQUAL "NEW")
  315. message(FATAL_ERROR "The WriteCompilerDetectionHeader module has been removed by policy CMP0120.")
  316. elseif(_WCDH_policy STREQUAL "")
  317. message(AUTHOR_WARNING
  318. "The WriteCompilerDetectionHeader module will be removed by policy CMP0120. "
  319. "Projects should be ported away from the module, perhaps by bundling a copy "
  320. "of the generated header or using a third-party alternative."
  321. )
  322. endif()
  323. include(${CMAKE_CURRENT_LIST_DIR}/CMakeCompilerIdDetection.cmake)
  324. function(_load_compiler_variables CompilerId lang)
  325. include("${CMAKE_ROOT}/Modules/Compiler/${CompilerId}-${lang}-FeatureTests.cmake" OPTIONAL)
  326. set(_cmake_oldestSupported_${CompilerId} ${_cmake_oldestSupported} PARENT_SCOPE)
  327. foreach(feature ${ARGN})
  328. set(_cmake_feature_test_${CompilerId}_${feature} ${_cmake_feature_test_${feature}} PARENT_SCOPE)
  329. endforeach()
  330. include("${CMAKE_ROOT}/Modules/Compiler/${CompilerId}-${lang}-DetermineCompiler.cmake" OPTIONAL
  331. RESULT_VARIABLE determinedCompiler)
  332. if (NOT determinedCompiler)
  333. include("${CMAKE_ROOT}/Modules/Compiler/${CompilerId}-DetermineCompiler.cmake" OPTIONAL)
  334. endif()
  335. set(_compiler_id_version_compute_${CompilerId} ${_compiler_id_version_compute} PARENT_SCOPE)
  336. endfunction()
  337. macro(_simpledefine FEATURE_NAME FEATURE_TESTNAME FEATURE_STRING FEATURE_DEFAULT_STRING)
  338. if (feature STREQUAL "${FEATURE_NAME}")
  339. set(def_value "${prefix_arg}_${FEATURE_TESTNAME}")
  340. string(APPEND file_content "
  341. # if defined(${def_name}) && ${def_name}
  342. # define ${def_value} ${FEATURE_STRING}
  343. # else
  344. # define ${def_value} ${FEATURE_DEFAULT_STRING}
  345. # endif
  346. \n")
  347. endif()
  348. endmacro()
  349. macro(_simplebaredefine FEATURE_NAME FEATURE_STRING FEATURE_DEFAULT_STRING)
  350. if (feature STREQUAL "${FEATURE_NAME}")
  351. string(APPEND file_content "
  352. # if !(defined(${def_name}) && ${def_name})
  353. # define ${FEATURE_STRING} ${FEATURE_DEFAULT_STRING}
  354. # endif
  355. \n")
  356. endif()
  357. endmacro()
  358. function(_check_feature_lists C_FEATURE_VAR CXX_FEATURE_VAR)
  359. foreach(feature ${ARGN})
  360. if (feature MATCHES "^c_std_")
  361. # ignored
  362. elseif (feature MATCHES "^cxx_std_")
  363. # ignored
  364. elseif (feature MATCHES "^cxx_")
  365. list(APPEND _langs CXX)
  366. list(APPEND ${CXX_FEATURE_VAR} ${feature})
  367. elseif (feature MATCHES "^c_")
  368. list(APPEND _langs C)
  369. list(APPEND ${C_FEATURE_VAR} ${feature})
  370. else()
  371. message(FATAL_ERROR "Unsupported feature ${feature}.")
  372. endif()
  373. endforeach()
  374. set(${C_FEATURE_VAR} ${${C_FEATURE_VAR}} PARENT_SCOPE)
  375. set(${CXX_FEATURE_VAR} ${${CXX_FEATURE_VAR}} PARENT_SCOPE)
  376. set(_langs ${_langs} PARENT_SCOPE)
  377. endfunction()
  378. function(write_compiler_detection_header
  379. file_keyword file_arg
  380. prefix_keyword prefix_arg
  381. )
  382. if (NOT "x${file_keyword}" STREQUAL "xFILE")
  383. message(FATAL_ERROR "write_compiler_detection_header: FILE parameter missing.")
  384. endif()
  385. if (NOT "x${prefix_keyword}" STREQUAL "xPREFIX")
  386. message(FATAL_ERROR "write_compiler_detection_header: PREFIX parameter missing.")
  387. endif()
  388. set(options ALLOW_UNKNOWN_COMPILERS ALLOW_UNKNOWN_COMPILER_VERSIONS)
  389. set(oneValueArgs VERSION EPILOG PROLOG OUTPUT_FILES_VAR OUTPUT_DIR)
  390. set(multiValueArgs COMPILERS FEATURES BARE_FEATURES)
  391. cmake_parse_arguments(_WCD "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  392. if (NOT _WCD_COMPILERS)
  393. message(FATAL_ERROR "Invalid arguments. write_compiler_detection_header requires at least one compiler.")
  394. endif()
  395. if (NOT _WCD_FEATURES AND NOT _WCD_BARE_FEATURES)
  396. message(FATAL_ERROR "Invalid arguments. write_compiler_detection_header requires at least one feature.")
  397. endif()
  398. if(_WCD_UNPARSED_ARGUMENTS)
  399. message(FATAL_ERROR "Unparsed arguments: ${_WCD_UNPARSED_ARGUMENTS}")
  400. endif()
  401. if (prefix_arg STREQUAL "")
  402. message(FATAL_ERROR "A prefix must be specified")
  403. endif()
  404. string(MAKE_C_IDENTIFIER ${prefix_arg} cleaned_prefix)
  405. if (NOT prefix_arg STREQUAL cleaned_prefix)
  406. message(FATAL_ERROR "The prefix must be a valid C identifier.")
  407. endif()
  408. if(NOT _WCD_VERSION)
  409. set(_WCD_VERSION ${CMAKE_MINIMUM_REQUIRED_VERSION})
  410. endif()
  411. set(_min_version 3.1.0) # Version which introduced this function
  412. if (_WCD_VERSION VERSION_LESS _min_version)
  413. set(err "VERSION compatibility for write_compiler_detection_header is set to ${_WCD_VERSION}, which is too low.")
  414. string(APPEND err " It must be set to at least ${_min_version}. ")
  415. string(APPEND err " Either set the VERSION parameter to the write_compiler_detection_header function, or update")
  416. string(APPEND err " your minimum required CMake version with the cmake_minimum_required command.")
  417. message(FATAL_ERROR "${err}")
  418. endif()
  419. if(_WCD_OUTPUT_FILES_VAR)
  420. if(NOT _WCD_OUTPUT_DIR)
  421. message(FATAL_ERROR "If OUTPUT_FILES_VAR is specified, then OUTPUT_DIR must also be specified.")
  422. endif()
  423. endif()
  424. if(_WCD_OUTPUT_DIR)
  425. if(NOT _WCD_OUTPUT_FILES_VAR)
  426. message(FATAL_ERROR "If OUTPUT_DIR is specified, then OUTPUT_FILES_VAR must also be specified.")
  427. endif()
  428. get_filename_component(main_file_dir ${file_arg} DIRECTORY)
  429. if (NOT IS_ABSOLUTE ${main_file_dir})
  430. set(main_file_dir "${CMAKE_CURRENT_BINARY_DIR}/${main_file_dir}")
  431. endif()
  432. if (NOT IS_ABSOLUTE ${_WCD_OUTPUT_DIR})
  433. set(_WCD_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${_WCD_OUTPUT_DIR}")
  434. endif()
  435. get_filename_component(out_file_dir ${_WCD_OUTPUT_DIR} ABSOLUTE)
  436. string(FIND ${out_file_dir} ${main_file_dir} idx)
  437. if (NOT idx EQUAL 0)
  438. message(FATAL_ERROR "The compiler-specific output directory must be within the same directory as the main file.")
  439. endif()
  440. if (main_file_dir STREQUAL out_file_dir)
  441. unset(_WCD_OUTPUT_DIR)
  442. else()
  443. string(REPLACE "${main_file_dir}/" "" _WCD_OUTPUT_DIR "${out_file_dir}/")
  444. endif()
  445. endif()
  446. set(compilers
  447. GNU
  448. Clang
  449. AppleClang
  450. MSVC
  451. SunPro
  452. Intel
  453. )
  454. set(_hex_compilers ADSP Borland Embarcadero SunPro)
  455. foreach(_comp ${_WCD_COMPILERS})
  456. list(FIND compilers ${_comp} idx)
  457. if (idx EQUAL -1)
  458. message(FATAL_ERROR "Unsupported compiler ${_comp}.")
  459. endif()
  460. if (NOT _need_hex_conversion)
  461. list(FIND _hex_compilers ${_comp} idx)
  462. if (NOT idx EQUAL -1)
  463. set(_need_hex_conversion TRUE)
  464. endif()
  465. endif()
  466. endforeach()
  467. set(file_content "
  468. // This is a generated file. Do not edit!
  469. #ifndef ${prefix_arg}_COMPILER_DETECTION_H
  470. #define ${prefix_arg}_COMPILER_DETECTION_H
  471. ")
  472. if (_WCD_PROLOG)
  473. string(APPEND file_content "\n${_WCD_PROLOG}\n")
  474. endif()
  475. if (_need_hex_conversion)
  476. string(APPEND file_content "
  477. #define ${prefix_arg}_DEC(X) (X)
  478. #define ${prefix_arg}_HEX(X) ( \\
  479. ((X)>>28 & 0xF) * 10000000 + \\
  480. ((X)>>24 & 0xF) * 1000000 + \\
  481. ((X)>>20 & 0xF) * 100000 + \\
  482. ((X)>>16 & 0xF) * 10000 + \\
  483. ((X)>>12 & 0xF) * 1000 + \\
  484. ((X)>>8 & 0xF) * 100 + \\
  485. ((X)>>4 & 0xF) * 10 + \\
  486. ((X) & 0xF) \\
  487. )\n")
  488. endif()
  489. _check_feature_lists(C_features CXX_features ${_WCD_FEATURES})
  490. _check_feature_lists(C_bare_features CXX_bare_features ${_WCD_BARE_FEATURES})
  491. list(REMOVE_DUPLICATES _langs)
  492. if(_WCD_OUTPUT_FILES_VAR)
  493. get_filename_component(main_file_name ${file_arg} NAME)
  494. set(compiler_file_content_
  495. "#ifndef ${prefix_arg}_COMPILER_DETECTION_H
  496. # error This file may only be included from ${main_file_name}
  497. #endif\n")
  498. endif()
  499. foreach(_lang ${_langs})
  500. set(target_compilers)
  501. foreach(compiler ${_WCD_COMPILERS})
  502. _load_compiler_variables(${compiler} ${_lang} ${${_lang}_features})
  503. if(_cmake_oldestSupported_${compiler})
  504. list(APPEND target_compilers ${compiler})
  505. endif()
  506. endforeach()
  507. get_property(known_features GLOBAL PROPERTY CMAKE_${_lang}_KNOWN_FEATURES)
  508. foreach(feature ${${_lang}_features})
  509. list(FIND known_features ${feature} idx)
  510. if (idx EQUAL -1)
  511. message(FATAL_ERROR "Unsupported feature ${feature}.")
  512. endif()
  513. endforeach()
  514. if(_lang STREQUAL CXX)
  515. string(APPEND file_content "\n#ifdef __cplusplus\n")
  516. else()
  517. string(APPEND file_content "\n#ifndef __cplusplus\n")
  518. endif()
  519. compiler_id_detection(ID_CONTENT ${_lang} PREFIX ${prefix_arg}_
  520. ID_DEFINE
  521. )
  522. string(APPEND file_content "${ID_CONTENT}\n")
  523. set(pp_if "if")
  524. foreach(compiler ${target_compilers})
  525. string(APPEND file_content "\n# ${pp_if} ${prefix_arg}_COMPILER_IS_${compiler}\n")
  526. if(_WCD_OUTPUT_FILES_VAR)
  527. set(compile_file_name "${_WCD_OUTPUT_DIR}${prefix_arg}_COMPILER_INFO_${compiler}_${_lang}.h")
  528. string(APPEND file_content "\n# include \"${compile_file_name}\"\n")
  529. endif()
  530. if(_WCD_OUTPUT_FILES_VAR)
  531. set(compiler_file_content compiler_file_content_${compiler}_${_lang})
  532. else()
  533. set(compiler_file_content file_content)
  534. endif()
  535. if(NOT _WCD_ALLOW_UNKNOWN_COMPILER_VERSIONS)
  536. string(APPEND ${compiler_file_content} "
  537. # if !(${_cmake_oldestSupported_${compiler}})
  538. # error Unsupported compiler version
  539. # endif\n")
  540. endif()
  541. set(PREFIX ${prefix_arg}_)
  542. if (_need_hex_conversion)
  543. set(MACRO_DEC ${prefix_arg}_DEC)
  544. set(MACRO_HEX ${prefix_arg}_HEX)
  545. else()
  546. set(MACRO_DEC)
  547. set(MACRO_HEX)
  548. endif()
  549. string(CONFIGURE "${_compiler_id_version_compute_${compiler}}" VERSION_BLOCK @ONLY)
  550. string(APPEND ${compiler_file_content} "${VERSION_BLOCK}\n")
  551. set(PREFIX)
  552. set(MACRO_DEC)
  553. set(MACRO_HEX)
  554. set(pp_if "elif")
  555. foreach(feature ${${_lang}_features})
  556. string(TOUPPER ${feature} feature_upper)
  557. set(feature_PP "COMPILER_${feature_upper}")
  558. set(_define_item "\n# define ${prefix_arg}_${feature_PP} 0\n")
  559. if (_cmake_feature_test_${compiler}_${feature} STREQUAL "1")
  560. set(_define_item "\n# define ${prefix_arg}_${feature_PP} 1\n")
  561. elseif (_cmake_feature_test_${compiler}_${feature})
  562. set(_define_item "\n# define ${prefix_arg}_${feature_PP} 0\n")
  563. set(_define_item "\n# if ${_cmake_feature_test_${compiler}_${feature}}\n# define ${prefix_arg}_${feature_PP} 1\n# else${_define_item}# endif\n")
  564. endif()
  565. string(APPEND ${compiler_file_content} "${_define_item}")
  566. endforeach()
  567. endforeach()
  568. if(pp_if STREQUAL "elif")
  569. if(_WCD_ALLOW_UNKNOWN_COMPILERS)
  570. string(APPEND file_content "
  571. # endif\n")
  572. else()
  573. string(APPEND file_content "
  574. # else
  575. # error Unsupported compiler
  576. # endif\n")
  577. endif()
  578. endif()
  579. foreach(feature ${${_lang}_features})
  580. string(TOUPPER ${feature} feature_upper)
  581. set(feature_PP "COMPILER_${feature_upper}")
  582. set(def_name ${prefix_arg}_${feature_PP})
  583. _simpledefine(c_restrict RESTRICT restrict "")
  584. _simpledefine(cxx_constexpr CONSTEXPR constexpr "")
  585. _simpledefine(cxx_final FINAL final "")
  586. _simpledefine(cxx_override OVERRIDE override "")
  587. if (feature STREQUAL cxx_static_assert)
  588. set(def_value "${prefix_arg}_STATIC_ASSERT(X)")
  589. set(def_value_msg "${prefix_arg}_STATIC_ASSERT_MSG(X, MSG)")
  590. set(def_fallback "enum { ${prefix_arg}_STATIC_ASSERT_JOIN(${prefix_arg}StaticAssertEnum, __LINE__) = sizeof(${prefix_arg}StaticAssert<X>) }")
  591. string(APPEND file_content "# if defined(${def_name}) && ${def_name}
  592. # define ${def_value} static_assert(X, #X)
  593. # define ${def_value_msg} static_assert(X, MSG)
  594. # else
  595. # define ${prefix_arg}_STATIC_ASSERT_JOIN(X, Y) ${prefix_arg}_STATIC_ASSERT_JOIN_IMPL(X, Y)
  596. # define ${prefix_arg}_STATIC_ASSERT_JOIN_IMPL(X, Y) X##Y
  597. template<bool> struct ${prefix_arg}StaticAssert;
  598. template<> struct ${prefix_arg}StaticAssert<true>{};
  599. # define ${def_value} ${def_fallback}
  600. # define ${def_value_msg} ${def_fallback}
  601. # endif
  602. \n")
  603. endif()
  604. if (feature STREQUAL cxx_alignas)
  605. set(def_value "${prefix_arg}_ALIGNAS(X)")
  606. string(APPEND file_content "
  607. # if defined(${def_name}) && ${def_name}
  608. # define ${def_value} alignas(X)
  609. # elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
  610. # define ${def_value} __attribute__ ((__aligned__(X)))
  611. # elif ${prefix_arg}_COMPILER_IS_MSVC
  612. # define ${def_value} __declspec(align(X))
  613. # else
  614. # define ${def_value}
  615. # endif
  616. \n")
  617. endif()
  618. if (feature STREQUAL cxx_alignof)
  619. set(def_value "${prefix_arg}_ALIGNOF(X)")
  620. string(APPEND file_content "
  621. # if defined(${def_name}) && ${def_name}
  622. # define ${def_value} alignof(X)
  623. # elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
  624. # define ${def_value} __alignof__(X)
  625. # elif ${prefix_arg}_COMPILER_IS_MSVC
  626. # define ${def_value} __alignof(X)
  627. # endif
  628. \n")
  629. endif()
  630. _simpledefine(cxx_deleted_functions DELETED_FUNCTION "= delete" "")
  631. _simpledefine(cxx_extern_templates EXTERN_TEMPLATE extern "")
  632. if (feature STREQUAL cxx_noexcept)
  633. set(def_value "${prefix_arg}_NOEXCEPT")
  634. string(APPEND file_content "
  635. # if defined(${def_name}) && ${def_name}
  636. # define ${def_value} noexcept
  637. # define ${def_value}_EXPR(X) noexcept(X)
  638. # else
  639. # define ${def_value}
  640. # define ${def_value}_EXPR(X)
  641. # endif
  642. \n")
  643. endif()
  644. if (feature STREQUAL cxx_nullptr)
  645. set(def_value "${prefix_arg}_NULLPTR")
  646. string(APPEND file_content "
  647. # if defined(${def_name}) && ${def_name}
  648. # define ${def_value} nullptr
  649. # elif ${prefix_arg}_COMPILER_IS_GNU
  650. # define ${def_value} __null
  651. # else
  652. # define ${def_value} 0
  653. # endif
  654. \n")
  655. endif()
  656. if (feature STREQUAL cxx_thread_local)
  657. set(def_value "${prefix_arg}_THREAD_LOCAL")
  658. string(APPEND file_content "
  659. # if defined(${def_name}) && ${def_name}
  660. # define ${def_value} thread_local
  661. # elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
  662. # define ${def_value} __thread
  663. # elif ${prefix_arg}_COMPILER_IS_MSVC
  664. # define ${def_value} __declspec(thread)
  665. # else
  666. // ${def_value} not defined for this configuration.
  667. # endif
  668. \n")
  669. endif()
  670. if (feature STREQUAL cxx_attribute_deprecated)
  671. set(def_name ${prefix_arg}_${feature_PP})
  672. set(def_value "${prefix_arg}_DEPRECATED")
  673. string(APPEND file_content "
  674. # ifndef ${def_value}
  675. # if defined(${def_name}) && ${def_name}
  676. # define ${def_value} [[deprecated]]
  677. # define ${def_value}_MSG(MSG) [[deprecated(MSG)]]
  678. # elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang
  679. # define ${def_value} __attribute__((__deprecated__))
  680. # define ${def_value}_MSG(MSG) __attribute__((__deprecated__(MSG)))
  681. # elif ${prefix_arg}_COMPILER_IS_MSVC
  682. # define ${def_value} __declspec(deprecated)
  683. # define ${def_value}_MSG(MSG) __declspec(deprecated(MSG))
  684. # else
  685. # define ${def_value}
  686. # define ${def_value}_MSG(MSG)
  687. # endif
  688. # endif
  689. \n")
  690. endif()
  691. endforeach()
  692. foreach(feature ${${_lang}_bare_features})
  693. string(TOUPPER ${feature} feature_upper)
  694. set(feature_PP "COMPILER_${feature_upper}")
  695. set(def_name ${prefix_arg}_${feature_PP})
  696. _simplebaredefine(c_restrict restrict "")
  697. _simplebaredefine(cxx_constexpr constexpr "")
  698. _simplebaredefine(cxx_final final "")
  699. _simplebaredefine(cxx_override override "")
  700. if (feature STREQUAL cxx_nullptr)
  701. set(def_value "nullptr")
  702. string(APPEND file_content "
  703. # if !(defined(${def_name}) && ${def_name})
  704. # if ${prefix_arg}_COMPILER_IS_GNU
  705. # define ${def_value} __null
  706. # else
  707. # define ${def_value} 0
  708. # endif
  709. # endif
  710. \n")
  711. endif()
  712. _simplebaredefine(cxx_noexcept noexcept "")
  713. endforeach()
  714. string(APPEND file_content "#endif\n")
  715. endforeach()
  716. if(_WCD_OUTPUT_FILES_VAR)
  717. foreach(compiler ${_WCD_COMPILERS})
  718. foreach(_lang ${_langs})
  719. if(compiler_file_content_${compiler}_${_lang})
  720. set(CMAKE_CONFIGURABLE_FILE_CONTENT "${compiler_file_content_}")
  721. string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT "${compiler_file_content_${compiler}_${_lang}}")
  722. set(compile_file_name "${_WCD_OUTPUT_DIR}${prefix_arg}_COMPILER_INFO_${compiler}_${_lang}.h")
  723. set(full_path "${main_file_dir}/${compile_file_name}")
  724. list(APPEND ${_WCD_OUTPUT_FILES_VAR} ${full_path})
  725. configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
  726. "${full_path}"
  727. @ONLY
  728. )
  729. endif()
  730. endforeach()
  731. endforeach()
  732. set(${_WCD_OUTPUT_FILES_VAR} ${${_WCD_OUTPUT_FILES_VAR}} PARENT_SCOPE)
  733. endif()
  734. if (_WCD_EPILOG)
  735. string(APPEND file_content "\n${_WCD_EPILOG}\n")
  736. endif()
  737. string(APPEND file_content "\n#endif")
  738. set(CMAKE_CONFIGURABLE_FILE_CONTENT ${file_content})
  739. configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
  740. "${file_arg}"
  741. @ONLY
  742. )
  743. endfunction()