CheckStructHasMember.cmake 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. ::
  20. CMAKE_REQUIRED_FLAGS = string of compile command line flags
  21. CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
  22. CMAKE_REQUIRED_INCLUDES = list of include directories
  23. CMAKE_REQUIRED_LINK_OPTIONS = list of options to pass to link command
  24. CMAKE_REQUIRED_LIBRARIES = list of libraries to link
  25. CMAKE_REQUIRED_QUIET = execute quietly without messages
  26. Example:
  27. .. code-block:: cmake
  28. CHECK_STRUCT_HAS_MEMBER("struct timeval" tv_sec sys/select.h
  29. HAVE_TIMEVAL_TV_SEC LANGUAGE C)
  30. #]=======================================================================]
  31. include_guard(GLOBAL)
  32. include(CheckCSourceCompiles)
  33. include(CheckCXXSourceCompiles)
  34. macro (CHECK_STRUCT_HAS_MEMBER _STRUCT _MEMBER _HEADER _RESULT)
  35. set(_INCLUDE_FILES)
  36. foreach (it ${_HEADER})
  37. string(APPEND _INCLUDE_FILES "#include <${it}>\n")
  38. endforeach ()
  39. if("x${ARGN}" STREQUAL "x")
  40. set(_lang C)
  41. elseif("x${ARGN}" MATCHES "^xLANGUAGE;([a-zA-Z]+)$")
  42. set(_lang "${CMAKE_MATCH_1}")
  43. else()
  44. message(FATAL_ERROR "Unknown arguments:\n ${ARGN}\n")
  45. endif()
  46. set(_CHECK_STRUCT_MEMBER_SOURCE_CODE "
  47. ${_INCLUDE_FILES}
  48. int main()
  49. {
  50. (void)sizeof(((${_STRUCT} *)0)->${_MEMBER});
  51. return 0;
  52. }
  53. ")
  54. if("${_lang}" STREQUAL "C")
  55. CHECK_C_SOURCE_COMPILES("${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
  56. elseif("${_lang}" STREQUAL "CXX")
  57. CHECK_CXX_SOURCE_COMPILES("${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
  58. else()
  59. message(FATAL_ERROR "Unknown language:\n ${_lang}\nSupported languages: C, CXX.\n")
  60. endif()
  61. endmacro ()