1# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2# file Copyright.txt or https://cmake.org/licensing for details.
3
4#[=======================================================================[.rst:
5CheckStructHasMember
6--------------------
7
8Check if the given struct or class has the specified member variable
9
10.. command:: CHECK_STRUCT_HAS_MEMBER
11
12  .. code-block:: cmake
13
14    CHECK_STRUCT_HAS_MEMBER(<struct> <member> <header> <variable>
15                            [LANGUAGE <language>])
16
17  ::
18
19    <struct> - the name of the struct or class you are interested in
20    <member> - the member which existence you want to check
21    <header> - the header(s) where the prototype should be declared
22    <variable> - variable to store the result
23    <language> - the compiler to use (C or CXX)
24
25
26The following variables may be set before calling this macro to modify
27the way the check is run:
28
29``CMAKE_REQUIRED_FLAGS``
30  string of compile command line flags.
31``CMAKE_REQUIRED_DEFINITIONS``
32  list of macros to define (-DFOO=bar).
33``CMAKE_REQUIRED_INCLUDES``
34  list of include directories.
35``CMAKE_REQUIRED_LINK_OPTIONS``
36  .. versionadded:: 3.14
37    list of options to pass to link command.
38``CMAKE_REQUIRED_LIBRARIES``
39  list of libraries to link.
40``CMAKE_REQUIRED_QUIET``
41  .. versionadded:: 3.1
42    execute quietly without messages.
43
44
45Example:
46
47.. code-block:: cmake
48
49  CHECK_STRUCT_HAS_MEMBER("struct timeval" tv_sec sys/select.h
50                          HAVE_TIMEVAL_TV_SEC LANGUAGE C)
51#]=======================================================================]
52
53include_guard(GLOBAL)
54include(CheckCSourceCompiles)
55include(CheckCXXSourceCompiles)
56
57macro (CHECK_STRUCT_HAS_MEMBER _STRUCT _MEMBER _HEADER _RESULT)
58  set(_INCLUDE_FILES)
59  foreach (it ${_HEADER})
60    string(APPEND _INCLUDE_FILES "#include <${it}>\n")
61  endforeach ()
62
63  if("x${ARGN}" STREQUAL "x")
64    set(_lang C)
65  elseif("x${ARGN}" MATCHES "^xLANGUAGE;([a-zA-Z]+)$")
66    set(_lang "${CMAKE_MATCH_1}")
67  else()
68    message(FATAL_ERROR "Unknown arguments:\n  ${ARGN}\n")
69  endif()
70
71  set(_CHECK_STRUCT_MEMBER_SOURCE_CODE "
72${_INCLUDE_FILES}
73int main()
74{
75  (void)sizeof(((${_STRUCT} *)0)->${_MEMBER});
76  return 0;
77}
78")
79
80  if("${_lang}" STREQUAL "C")
81    CHECK_C_SOURCE_COMPILES("${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
82  elseif("${_lang}" STREQUAL "CXX")
83    CHECK_CXX_SOURCE_COMPILES("${_CHECK_STRUCT_MEMBER_SOURCE_CODE}" ${_RESULT})
84  else()
85    message(FATAL_ERROR "Unknown language:\n  ${_lang}\nSupported languages: C, CXX.\n")
86  endif()
87endmacro ()
88