CheckTypeSize.cmake 10.0 KB

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