CheckTypeSize.cmake 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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_LINK_DIRECTORIES.txt
  54. .. include:: /module/CMAKE_REQUIRED_QUIET.txt
  55. ``CMAKE_EXTRA_INCLUDE_FILES``
  56. list of extra headers to include.
  57. #]=======================================================================]
  58. include(CheckIncludeFile)
  59. include(CheckIncludeFileCXX)
  60. get_filename_component(__check_type_size_dir "${CMAKE_CURRENT_LIST_FILE}" PATH)
  61. include_guard(GLOBAL)
  62. block(SCOPE_FOR POLICIES)
  63. cmake_policy(SET CMP0054 NEW)
  64. cmake_policy(SET CMP0159 NEW) # file(STRINGS) with REGEX updates CMAKE_MATCH_<n>
  65. #-----------------------------------------------------------------------------
  66. # Helper function. DO NOT CALL DIRECTLY.
  67. function(__check_type_size_impl type var map builtin language)
  68. if(NOT CMAKE_REQUIRED_QUIET)
  69. message(CHECK_START "Check size of ${type}")
  70. endif()
  71. # Perform language check
  72. string(MAKE_C_IDENTIFIER ${var} _var_escaped)
  73. if(language STREQUAL "C")
  74. set(src ${_var_escaped}.c)
  75. elseif(language STREQUAL "CXX")
  76. set(src ${_var_escaped}.cpp)
  77. else()
  78. message(FATAL_ERROR "Unknown language:\n ${language}\nSupported languages: C, CXX.\n")
  79. endif()
  80. # Include header files.
  81. set(headers)
  82. if(builtin)
  83. if(language STREQUAL "CXX" AND type MATCHES "^std::")
  84. if(HAVE_SYS_TYPES_H)
  85. string(APPEND headers "#include <sys/types.h>\n")
  86. endif()
  87. if(HAVE_CSTDINT)
  88. string(APPEND headers "#include <cstdint>\n")
  89. endif()
  90. if(HAVE_CSTDDEF)
  91. string(APPEND headers "#include <cstddef>\n")
  92. endif()
  93. else()
  94. if(HAVE_SYS_TYPES_H)
  95. string(APPEND headers "#include <sys/types.h>\n")
  96. endif()
  97. if(HAVE_STDINT_H)
  98. string(APPEND headers "#include <stdint.h>\n")
  99. endif()
  100. if(HAVE_STDDEF_H)
  101. string(APPEND headers "#include <stddef.h>\n")
  102. endif()
  103. endif()
  104. endif()
  105. foreach(h ${CMAKE_EXTRA_INCLUDE_FILES})
  106. string(APPEND headers "#include \"${h}\"\n")
  107. endforeach()
  108. if(CMAKE_REQUIRED_LINK_DIRECTORIES)
  109. set(_CTS_LINK_DIRECTORIES
  110. "-DLINK_DIRECTORIES:STRING=${CMAKE_REQUIRED_LINK_DIRECTORIES}")
  111. else()
  112. set(_CTS_LINK_DIRECTORIES)
  113. endif()
  114. # Perform the check.
  115. set(bin ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CheckTypeSize/${var}.bin)
  116. file(READ ${__check_type_size_dir}/CheckTypeSize.c.in src_content)
  117. string(CONFIGURE "${src_content}" src_content @ONLY)
  118. try_compile(HAVE_${var} SOURCE_FROM_VAR "${src}" src_content
  119. COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
  120. LINK_OPTIONS ${CMAKE_REQUIRED_LINK_OPTIONS}
  121. LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
  122. CMAKE_FLAGS
  123. "-DCOMPILE_DEFINITIONS:STRING=${CMAKE_REQUIRED_FLAGS}"
  124. "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}"
  125. "${_CTS_LINK_DIRECTORIES}"
  126. COPY_FILE ${bin}
  127. )
  128. unset(_CTS_LINK_DIRECTORIES)
  129. if(HAVE_${var})
  130. # The check compiled. Load information from the binary.
  131. file(STRINGS ${bin} strings LIMIT_COUNT 10 REGEX "INFO:size")
  132. # Parse the information strings.
  133. set(regex_size ".*INFO:size\\[0*([^]]*)\\].*")
  134. set(regex_key " key\\[([^]]*)\\]")
  135. set(keys)
  136. set(code)
  137. set(mismatch)
  138. set(first 1)
  139. foreach(info ${strings})
  140. if("${info}" MATCHES "${regex_size}")
  141. # Get the type size.
  142. set(size "${CMAKE_MATCH_1}")
  143. if(first)
  144. set(${var} ${size})
  145. elseif(NOT "${size}" STREQUAL "${${var}}")
  146. set(mismatch 1)
  147. endif()
  148. set(first 0)
  149. # Get the architecture map key.
  150. string(REGEX MATCH "${regex_key}" key "${info}")
  151. string(REGEX REPLACE "${regex_key}" "\\1" key "${key}")
  152. if(key)
  153. string(APPEND code "\nset(${var}-${key} \"${size}\")")
  154. list(APPEND keys ${key})
  155. endif()
  156. endif()
  157. endforeach()
  158. # Update the architecture-to-size map.
  159. if(mismatch AND keys)
  160. configure_file(${__check_type_size_dir}/CheckTypeSizeMap.cmake.in ${map} @ONLY)
  161. set(${var} 0)
  162. else()
  163. file(REMOVE ${map})
  164. endif()
  165. if(mismatch AND NOT keys)
  166. 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 !")
  167. endif()
  168. if(NOT CMAKE_REQUIRED_QUIET)
  169. message(CHECK_PASS "done")
  170. endif()
  171. set(${var} "${${var}}" CACHE INTERNAL "CHECK_TYPE_SIZE: sizeof(${type})")
  172. else()
  173. # The check failed to compile.
  174. if(NOT CMAKE_REQUIRED_QUIET)
  175. message(CHECK_FAIL "failed")
  176. endif()
  177. set(${var} "" CACHE INTERNAL "CHECK_TYPE_SIZE: ${type} unknown")
  178. file(REMOVE ${map})
  179. endif()
  180. endfunction()
  181. #-----------------------------------------------------------------------------
  182. macro(CHECK_TYPE_SIZE TYPE VARIABLE)
  183. # parse arguments
  184. unset(doing)
  185. foreach(arg ${ARGN})
  186. if("x${arg}" STREQUAL "xBUILTIN_TYPES_ONLY")
  187. set(_CHECK_TYPE_SIZE_${arg} 1)
  188. unset(doing)
  189. elseif("x${arg}" STREQUAL "xLANGUAGE") # change to MATCHES for more keys
  190. set(doing "${arg}")
  191. set(_CHECK_TYPE_SIZE_${doing} "")
  192. elseif("x${doing}" STREQUAL "xLANGUAGE")
  193. set(_CHECK_TYPE_SIZE_${doing} "${arg}")
  194. unset(doing)
  195. else()
  196. message(FATAL_ERROR "Unknown argument:\n ${arg}\n")
  197. endif()
  198. endforeach()
  199. if("x${doing}" MATCHES "^x(LANGUAGE)$")
  200. message(FATAL_ERROR "Missing argument:\n ${doing} arguments requires a value\n")
  201. endif()
  202. if(DEFINED _CHECK_TYPE_SIZE_LANGUAGE)
  203. if(NOT "x${_CHECK_TYPE_SIZE_LANGUAGE}" MATCHES "^x(C|CXX)$")
  204. message(FATAL_ERROR "Unknown language:\n ${_CHECK_TYPE_SIZE_LANGUAGE}.\nSupported languages: C, CXX.\n")
  205. endif()
  206. set(_language ${_CHECK_TYPE_SIZE_LANGUAGE})
  207. else()
  208. set(_language C)
  209. endif()
  210. # Optionally check for standard headers.
  211. if(_CHECK_TYPE_SIZE_BUILTIN_TYPES_ONLY)
  212. set(_builtin 0)
  213. else()
  214. set(_builtin 1)
  215. if(_language STREQUAL "C")
  216. check_include_file(sys/types.h HAVE_SYS_TYPES_H)
  217. check_include_file(stdint.h HAVE_STDINT_H)
  218. check_include_file(stddef.h HAVE_STDDEF_H)
  219. elseif(_language STREQUAL "CXX")
  220. check_include_file_cxx(sys/types.h HAVE_SYS_TYPES_H)
  221. if("${TYPE}" MATCHES "^std::")
  222. check_include_file_cxx(cstdint HAVE_CSTDINT)
  223. check_include_file_cxx(cstddef HAVE_CSTDDEF)
  224. else()
  225. check_include_file_cxx(stdint.h HAVE_STDINT_H)
  226. check_include_file_cxx(stddef.h HAVE_STDDEF_H)
  227. endif()
  228. endif()
  229. endif()
  230. unset(_CHECK_TYPE_SIZE_BUILTIN_TYPES_ONLY)
  231. unset(_CHECK_TYPE_SIZE_LANGUAGE)
  232. # Compute or load the size or size map.
  233. set(${VARIABLE}_KEYS)
  234. set(_map_file ${CMAKE_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/CheckTypeSize/${VARIABLE}.cmake)
  235. if(NOT DEFINED HAVE_${VARIABLE})
  236. __check_type_size_impl(${TYPE} ${VARIABLE} ${_map_file} ${_builtin} ${_language})
  237. endif()
  238. include(${_map_file} OPTIONAL)
  239. set(_map_file)
  240. set(_builtin)
  241. # Create preprocessor code.
  242. if(${VARIABLE}_KEYS)
  243. set(${VARIABLE}_CODE)
  244. set(_if if)
  245. foreach(key ${${VARIABLE}_KEYS})
  246. string(APPEND ${VARIABLE}_CODE "#${_if} defined(${key})\n# define ${VARIABLE} ${${VARIABLE}-${key}}\n")
  247. set(_if elif)
  248. endforeach()
  249. string(APPEND ${VARIABLE}_CODE "#else\n# error ${VARIABLE} unknown\n#endif")
  250. set(_if)
  251. elseif(${VARIABLE})
  252. set(${VARIABLE}_CODE "#define ${VARIABLE} ${${VARIABLE}}")
  253. else()
  254. set(${VARIABLE}_CODE "/* #undef ${VARIABLE} */")
  255. endif()
  256. endmacro()
  257. #-----------------------------------------------------------------------------
  258. endblock()