WriteCompilerDetectionHeader.cmake 31 KB

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