CheckStructHasMember.cmake 2.3 KB

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