cmakecmake-modules

cmake check if a public field exist in class


// some_library.h
class MyLib {
  public:
  int field_a;
  int field_b; // Only available on some versions
  int field_c; // Only available on some versions
  int ...;
};

A library I'm using have a variable number of public fields depending on versions. In Cmake, is it possible to detect if a certain field from library header exists? (perhaps similar to the CHECK_FUNCTION_EXISTS)


Solution

  • You can use check_symbol_exists for a C symbol.

    Doc: https://cmake.org/cmake/help/latest/module/CheckSymbolExists.html

    Or check_cxx_symbol_exists for a CXX symbol.

    Doc: https://cmake.org/cmake/help/v3.18/module/CheckCXXSymbolExists.html

    You can use check_struct_has_member from CheckStructHasMember. See https://cmake.org/cmake/help/latest/module/CheckStructHasMember.html

    CMakeLists.txt

    include(CheckStructHasMember)
    Check_struct_has_member("class MyLib" field_a ${CMAKE_CURRENT_SOURCE_DIR}/MyLib.h HAS_FIELD_A LANGUAGE CXX)