CheckTypeSize.cmake 9.4 KB

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