CheckStructHasMember.cmake 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. CheckStructHasMember
  5. --------------------
  6. Check if the given struct or class has the specified member variable
  7. .. command:: CHECK_STRUCT_HAS_MEMBER
  8. .. code-block:: cmake
  9. CHECK_STRUCT_HAS_MEMBER(<struct> <member> <header> <variable>
  10. [LANGUAGE <language>])
  11. ::
  12. <struct> - the name of the struct or class you are interested in
  13. <member> - the member which existence you want to check
  14. <header> - the header(s) where the prototype should be declared
  15. <variable> - variable to store the result
  16. <language> - the compiler to use (C or CXX)
  17. The following variables may be set before calling this macro to modify
  18. the way the check is run:
  19. .. include:: /module/CMAKE_REQUIRED_FLAGS.txt
  20. .. include:: /module/CMAKE_REQUIRED_DEFINITIONS.txt
  21. .. include:: /module/CMAKE_REQUIRED_INCLUDES.txt
  22. .. include:: /module/CMAKE_REQUIRED_LINK_OPTIONS.txt
  23. .. include:: /module/CMAKE_REQUIRED_LIBRARIES.txt
  24. .. include:: /module/CMAKE_REQUIRED_QUIET.txt
  25. Example:
  26. .. code-block:: cmake
  27. CHECK_STRUCT_HAS_MEMBER("struct timeval" tv_sec sys/select.h
  28. HAVE_TIMEVAL_TV_SEC LANGUAGE C)
  29. #]=======================================================================]
  30. include_guard(GLOBAL)
  31. include(CheckSourceCompiles)
  32. macro (CHECK_STRUCT_HAS_MEMBER _STRUCT _MEMBER _HEADER _RESULT)
  33. set(_INCLUDE_FILES)
  34. foreach (it ${_HEADER})
  35. string(APPEND _INCLUDE_FILES "#include <${it}>\n")
  36. endforeach ()
  37. if("x${ARGN}" STREQUAL "x")
  38. set(_lang C)
  39. elseif("x${ARGN}" MATCHES "^xLANGUAGE;([a-zA-Z]+)$")
  40. set(_lang "${CMAKE_MATCH_1}")
  41. else()
  42. message(FATAL_ERROR "Unknown arguments:\n ${ARGN}\n")
  43. endif()
  44. set(_CHECK_STRUCT_MEMBER_SOURCE_CODE "
  45. ${_INCLUDE_FILES}
  46. int main()
  47. {
  48. (void)sizeof(((${_STRUCT} *)0)->${_MEMBER});
  49. return 0;
  50. }
  51. ")
  52. if("${_lang}" STREQUAL "C")
  53. CHECK_SOURCE_COMPILES(C "${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
  54. elseif("${_lang}" STREQUAL "CXX")
  55. CHECK_SOURCE_COMPILES(CXX "${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
  56. else()
  57. message(FATAL_ERROR "Unknown language:\n ${_lang}\nSupported languages: C, CXX.\n")
  58. endif()
  59. endmacro ()
  60. # FIXME(#24994): The following modules are included only for compatibility
  61. # with projects that accidentally relied on them with CMake 3.26 and below.
  62. include(CheckCSourceCompiles)
  63. include(CheckCXXSourceCompiles)