How to automatically generate a C header file using CMake?

I am looking for a way to automatically create a header file. This file is the public interface of the library, and I want to "fill in" some structures and materials before compilation.

For example, in a closed header, I have a structure with useful fields:

typedef struct mystuff_attr_t {
  int                      _detachstate;
  mystuff_scope_t          _scope;
  cpu_set_t                _cpuset;
  size_t                   _stacksize;
  void*                    _stackaddr;
} mystuff_attr_t;

And I would like to have this structure in a public header with no fields, but with the same size (currently executed manually) as follows:

typedef struct mystuff_attr_t {
  char _opaque[ 20 ]; 
} mystuff_attr_t;

I would like this to be automatically generated by CMake when creating the build system in order to avoid the poor size structure in the open interface when I change the structure in the closed header.

+3
source share
3

CMake ( configure_file (file.h.in file.h)), ( check_type_size ("type" header.h)), , . , CMakeList.txt:

# Where to search for types :
set (CMAKE_EXTRA_INCLUDE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/private_type.h)

# Type1 :
check_type_size ("type1_t" MY_SIZEOF_TYPE1_T)

# Generate public header :
configure_file (${CMAKE_CURRENT_SOURCE_DIR}/pub_type.h.in ${CMAKE_CURRENT_BINARY_DIR}/pub_type.h)

# Need to set this back to nothing :
set (CMAKE_EXTRA_INCLUDE_FILES)

pub_type.h.in:

#define MY_SIZEOF_TYPE1_T ${MY_SIZEOF_TYPE1_T}

:)

+9
+3

I would write an exe that creates the header.

eg:

#include <stdio.h>

#define PUBLIC(TYPE) \
printf( "typedef struct %s { char _opaque[ %d ]; } %s;\n", #TYPE, sizeof(TYPE), #TYPE )

int main()
  {
  // start header stuff

  PUBLIC(mystuff_attr_t);

  // end header stuff
  }
+2
source

Source: https://habr.com/ru/post/1704639/


All Articles