CheckStructHasMember.cmake 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #
  7. # Check if the given struct or class has the specified member variable
  8. #
  9. # ::
  10. #
  11. # CHECK_STRUCT_HAS_MEMBER(<struct> <member> <header> <variable>
  12. # [LANGUAGE <language>])
  13. #
  14. # ::
  15. #
  16. # <struct> - the name of the struct or class you are interested in
  17. # <member> - the member which existence you want to check
  18. # <header> - the header(s) where the prototype should be declared
  19. # <variable> - variable to store the result
  20. # <language> - the compiler to use (C or CXX)
  21. #
  22. #
  23. #
  24. # The following variables may be set before calling this macro to modify
  25. # the way the check is run:
  26. #
  27. # ::
  28. #
  29. # CMAKE_REQUIRED_FLAGS = string of compile command line flags
  30. # CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
  31. # CMAKE_REQUIRED_INCLUDES = list of include directories
  32. # CMAKE_REQUIRED_LIBRARIES = list of libraries to link
  33. # CMAKE_REQUIRED_QUIET = execute quietly without messages
  34. #
  35. #
  36. #
  37. # Example: CHECK_STRUCT_HAS_MEMBER("struct timeval" tv_sec sys/select.h
  38. # HAVE_TIMEVAL_TV_SEC LANGUAGE C)
  39. include_guard(GLOBAL)
  40. include(CheckCSourceCompiles)
  41. include(CheckCXXSourceCompiles)
  42. macro (CHECK_STRUCT_HAS_MEMBER _STRUCT _MEMBER _HEADER _RESULT)
  43. set(_INCLUDE_FILES)
  44. foreach (it ${_HEADER})
  45. string(APPEND _INCLUDE_FILES "#include <${it}>\n")
  46. endforeach ()
  47. if("x${ARGN}" STREQUAL "x")
  48. set(_lang C)
  49. elseif("x${ARGN}" MATCHES "^xLANGUAGE;([a-zA-Z]+)$")
  50. set(_lang "${CMAKE_MATCH_1}")
  51. else()
  52. message(FATAL_ERROR "Unknown arguments:\n ${ARGN}\n")
  53. endif()
  54. set(_CHECK_STRUCT_MEMBER_SOURCE_CODE "
  55. ${_INCLUDE_FILES}
  56. int main()
  57. {
  58. (void)sizeof(((${_STRUCT} *)0)->${_MEMBER});
  59. return 0;
  60. }
  61. ")
  62. if("${_lang}" STREQUAL "C")
  63. CHECK_C_SOURCE_COMPILES("${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
  64. elseif("${_lang}" STREQUAL "CXX")
  65. CHECK_CXX_SOURCE_COMPILES("${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
  66. else()
  67. message(FATAL_ERROR "Unknown language:\n ${_lang}\nSupported languages: C, CXX.\n")
  68. endif()
  69. endmacro ()