CheckTypeSize.cmake 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. CheckTypeSize
  5. -------------
  6. Check sizeof a type
  7. .. command:: check_type_size
  8. .. code-block:: cmake
  9. check_type_size(<type> <variable> [BUILTIN_TYPES_ONLY]
  10. [LANGUAGE <language>])
  11. Check if the type exists and determine its size. Results are reported
  12. in the following variables:
  13. ``HAVE_<variable>``
  14. Holds a true or false value indicating whether the type exists.
  15. ``<variable>``
  16. Holds one of the following values:
  17. ``<size>``
  18. Type has non-zero size ``<size>``.
  19. ``0``
  20. Type has architecture-dependent size. This may occur when
  21. :variable:`CMAKE_OSX_ARCHITECTURES` has multiple architectures.
  22. In this case ``<variable>_CODE`` contains C preprocessor tests
  23. mapping from each architecture macro to the corresponding type size.
  24. The list of architecture macros is stored in ``<variable>_KEYS``,
  25. and the value for each key is stored in ``<variable>-<key>``.
  26. "" (empty string)
  27. Type does not exist.
  28. ``<variable>_CODE``
  29. Holds C preprocessor code to define the macro ``<variable>`` to the size
  30. of the type, or to leave the macro undefined if the type does not exist.
  31. The options are:
  32. ``BUILTIN_TYPES_ONLY``
  33. Support only compiler-builtin types. If *not* given, the macro checks
  34. for headers ``<sys/types.h>``, ``<stdint.h>``, and ``<stddef.h>``, and
  35. saves results in ``HAVE_SYS_TYPES_H``, ``HAVE_STDINT_H``, and
  36. ``HAVE_STDDEF_H``. The type size check automatically includes the
  37. available headers, thus supporting checks of types defined in the headers.
  38. ``LANGUAGE <language>``
  39. Use the ``<language>`` compiler to perform the check.
  40. Acceptable values are ``C`` and ``CXX``.
  41. Despite the name of the macro you may use it to check the size of more
  42. complex expressions, too. To check e.g. for the size of a struct
  43. member you can do something like this:
  44. .. code-block:: cmake
  45. check_type_size("((struct something*)0)->member" SIZEOF_MEMBER)
  46. The following variables may be set before calling this macro to modify
  47. the way the check is run:
  48. .. include:: /module/CMAKE_REQUIRED_FLAGS.txt
  49. .. include:: /module/CMAKE_REQUIRED_DEFINITIONS.txt
  50. .. include:: /module/CMAKE_REQUIRED_INCLUDES.txt
  51. .. include:: /module/CMAKE_REQUIRED_LINK_OPTIONS.txt
  52. .. include:: /module/CMAKE_REQUIRED_LIBRARIES.txt
  53. .. include:: /module/CMAKE_REQUIRED_QUIET.txt
  54. ``CMAKE_EXTRA_INCLUDE_FILES``
  55. list of extra headers to include.
  56. #]=======================================================================]
  57. include(CheckIncludeFile)
  58. include(CheckIncludeFileCXX)
  59. get_filename_component(__check_type_size_dir "${CMAKE_CURRENT_LIST_FILE}" PATH)
  60. include_guard(GLOBAL)
  61. block(SCOPE_FOR POLICIES)
  62. cmake_policy(SET CMP0054 NEW)
  63. cmake_policy(SET CMP0159 NEW) # file(STRINGS) with REGEX updates CMAKE_MATCH_<n>
  64. #-----------------------------------------------------------------------------
  65. # Helper function. DO NOT CALL DIRECTLY.
  66. function(__check_type_size_impl type var map builtin language)
  67. if(NOT CMAKE_REQUIRED_QUIET)
  68. message(CHECK_START "Check size of ${type}")
  69. endif()
  70. # Perform language check
  71. string(MAKE_C_IDENTIFIER ${var} _var_escaped)
  72. if(language STREQUAL "C")
  73. set(src ${_var_escaped}.c)
  74. elseif(language STREQUAL "CXX")
  75. set(src ${_var_escaped}.cpp)
  76. else()
  77. message(FATAL_ERROR "Unknown language:\n ${language}\nSupported languages: C, CXX.\n")
  78. endif()
  79. # Include header files.
  80. set(headers)
  81. if(builtin)
  82. if(language STREQUAL "CXX" AND type MATCHES "^std::")
  83. if(HAVE_SYS_TYPES_H)
  84. string(APPEND headers "#include <sys/types.h>\n")
  85. endif()
  86. if(HAVE_CSTDINT)
  87. string(APPEND headers "#include <cstdint>\n")
  88. endif()
  89. if(HAVE_CSTDDEF)
  90. string(APPEND headers "#include <cstddef>\n")
  91. endif()
  92. else()
  93. if(HAVE_SYS_TYPES_H)
  94. string(APPEND headers "#include <sys/types.h>\n")
  95. endif()
  96. if(HAVE_STDINT_H)
  97. string(APPEND headers "#include <stdint.h>\n")
  98. endif()
  99. if(HAVE_STDDEF_H)
  100. string(APPEND headers "#include <stddef.h>\n")
  101. endif()
  102. endif()
  103. endif()
  104. foreach(h ${CMAKE_EXTRA_INCLUDE_FILES})
  105. string(APPEND headers "#include \"${h}\"\n")
  106. endforeach()
  107. # Perform the check.
  108. set(bin ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CheckTypeSize/${var}.bin)
  109. file(READ ${__check_type_size_dir}/CheckTypeSize.c.in src_content)
  110. string(CONFIGURE "${src_content}" src_content @ONLY)
  111. try_compile(HAVE_${var} SOURCE_FROM_VAR "${src}" src_content
  112. COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
  113. LINK_OPTIONS ${CMAKE_REQUIRED_LINK_OPTIONS}
  114. LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
  115. CMAKE_FLAGS
  116. "-DCOMPILE_DEFINITIONS:STRING=${CMAKE_REQUIRED_FLAGS}"
  117. "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}"
  118. COPY_FILE ${bin}
  119. )
  120. if(HAVE_${var})
  121. # The check compiled. Load information from the binary.
  122. file(STRINGS ${bin} strings LIMIT_COUNT 10 REGEX "INFO:size")
  123. # Parse the information strings.
  124. set(regex_size ".*INFO:size\\[0*([^]]*)\\].*")
  125. set(regex_key " key\\[([^]]*)\\]")
  126. set(keys)
  127. set(code)
  128. set(mismatch)
  129. set(first 1)
  130. foreach(info ${strings})
  131. if("${info}" MATCHES "${regex_size}")
  132. # Get the type size.
  133. set(size "${CMAKE_MATCH_1}")
  134. if(first)
  135. set(${var} ${size})
  136. elseif(NOT "${size}" STREQUAL "${${var}}")
  137. set(mismatch 1)
  138. endif()
  139. set(first 0)
  140. # Get the architecture map key.
  141. string(REGEX MATCH "${regex_key}" key "${info}")
  142. string(REGEX REPLACE "${regex_key}" "\\1" key "${key}")
  143. if(key)
  144. string(APPEND code "\nset(${var}-${key} \"${size}\")")
  145. list(APPEND keys ${key})
  146. endif()
  147. endif()
  148. endforeach()
  149. # Update the architecture-to-size map.
  150. if(mismatch AND keys)
  151. configure_file(${__check_type_size_dir}/CheckTypeSizeMap.cmake.in ${map} @ONLY)
  152. set(${var} 0)
  153. else()
  154. file(REMOVE ${map})
  155. endif()
  156. if(mismatch AND NOT keys)
  157. message(SEND_ERROR "CHECK_TYPE_SIZE found different results, consider setting CMAKE_OSX_ARCHITECTURES or CMAKE_TRY_COMPILE_OSX_ARCHITECTURES to one or no architecture !")
  158. endif()
  159. if(NOT CMAKE_REQUIRED_QUIET)
  160. message(CHECK_PASS "done")
  161. endif()
  162. set(${var} "${${var}}" CACHE INTERNAL "CHECK_TYPE_SIZE: sizeof(${type})")
  163. else()
  164. # The check failed to compile.
  165. if(NOT CMAKE_REQUIRED_QUIET)
  166. message(CHECK_FAIL "failed")
  167. endif()
  168. set(${var} "" CACHE INTERNAL "CHECK_TYPE_SIZE: ${type} unknown")
  169. file(REMOVE ${map})
  170. endif()
  171. endfunction()
  172. #-----------------------------------------------------------------------------
  173. macro(CHECK_TYPE_SIZE TYPE VARIABLE)
  174. # parse arguments
  175. unset(doing)
  176. foreach(arg ${ARGN})
  177. if("x${arg}" STREQUAL "xBUILTIN_TYPES_ONLY")
  178. set(_CHECK_TYPE_SIZE_${arg} 1)
  179. unset(doing)
  180. elseif("x${arg}" STREQUAL "xLANGUAGE") # change to MATCHES for more keys
  181. set(doing "${arg}")
  182. set(_CHECK_TYPE_SIZE_${doing} "")
  183. elseif("x${doing}" STREQUAL "xLANGUAGE")
  184. set(_CHECK_TYPE_SIZE_${doing} "${arg}")
  185. unset(doing)
  186. else()
  187. message(FATAL_ERROR "Unknown argument:\n ${arg}\n")
  188. endif()
  189. endforeach()
  190. if("x${doing}" MATCHES "^x(LANGUAGE)$")
  191. message(FATAL_ERROR "Missing argument:\n ${doing} arguments requires a value\n")
  192. endif()
  193. if(DEFINED _CHECK_TYPE_SIZE_LANGUAGE)
  194. if(NOT "x${_CHECK_TYPE_SIZE_LANGUAGE}" MATCHES "^x(C|CXX)$")
  195. message(FATAL_ERROR "Unknown language:\n ${_CHECK_TYPE_SIZE_LANGUAGE}.\nSupported languages: C, CXX.\n")
  196. endif()
  197. set(_language ${_CHECK_TYPE_SIZE_LANGUAGE})
  198. else()
  199. set(_language C)
  200. endif()
  201. # Optionally check for standard headers.
  202. if(_CHECK_TYPE_SIZE_BUILTIN_TYPES_ONLY)
  203. set(_builtin 0)
  204. else()
  205. set(_builtin 1)
  206. if(_language STREQUAL "C")
  207. check_include_file(sys/types.h HAVE_SYS_TYPES_H)
  208. check_include_file(stdint.h HAVE_STDINT_H)
  209. check_include_file(stddef.h HAVE_STDDEF_H)
  210. elseif(_language STREQUAL "CXX")
  211. check_include_file_cxx(sys/types.h HAVE_SYS_TYPES_H)
  212. if("${TYPE}" MATCHES "^std::")
  213. check_include_file_cxx(cstdint HAVE_CSTDINT)
  214. check_include_file_cxx(cstddef HAVE_CSTDDEF)
  215. else()
  216. check_include_file_cxx(stdint.h HAVE_STDINT_H)
  217. check_include_file_cxx(stddef.h HAVE_STDDEF_H)
  218. endif()
  219. endif()
  220. endif()
  221. unset(_CHECK_TYPE_SIZE_BUILTIN_TYPES_ONLY)
  222. unset(_CHECK_TYPE_SIZE_LANGUAGE)
  223. # Compute or load the size or size map.
  224. set(${VARIABLE}_KEYS)
  225. set(_map_file ${CMAKE_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/CheckTypeSize/${VARIABLE}.cmake)
  226. if(NOT DEFINED HAVE_${VARIABLE})
  227. __check_type_size_impl(${TYPE} ${VARIABLE} ${_map_file} ${_builtin} ${_language})
  228. endif()
  229. include(${_map_file} OPTIONAL)
  230. set(_map_file)
  231. set(_builtin)
  232. # Create preprocessor code.
  233. if(${VARIABLE}_KEYS)
  234. set(${VARIABLE}_CODE)
  235. set(_if if)
  236. foreach(key ${${VARIABLE}_KEYS})
  237. string(APPEND ${VARIABLE}_CODE "#${_if} defined(${key})\n# define ${VARIABLE} ${${VARIABLE}-${key}}\n")
  238. set(_if elif)
  239. endforeach()
  240. string(APPEND ${VARIABLE}_CODE "#else\n# error ${VARIABLE} unknown\n#endif")
  241. set(_if)
  242. elseif(${VARIABLE})
  243. set(${VARIABLE}_CODE "#define ${VARIABLE} ${${VARIABLE}}")
  244. else()
  245. set(${VARIABLE}_CODE "/* #undef ${VARIABLE} */")
  246. endif()
  247. endmacro()
  248. #-----------------------------------------------------------------------------
  249. endblock()