CheckTypeSize.cmake 9.9 KB

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