Preprocessor loop over sequence of header files

761 views Asked by At

Is it possible to include a sequence of files: file1,file2,file3 in a preprocessor loop?

#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/cat.hpp>

// needed whitespace here----*
#define BOOST_PP_LOCAL_LIMITS (1, 3)

#define GENERATE_FILE_NAME(n) \
   BOOST_PP_STRINGIZE( BOOST_PP_CAT( file , n) ) \
   /**/

#define BOOST_PP_LOCAL_MACRO(n) \
    #include GENERATE_FILE_NAME(n) \

and then using it with:

#include BOOST_PP_LOCAL_ITERATE()

should expand to

BOOST_PP_LOCAL_MACRO(1) --> includes file1
BOOST_PP_LOCAL_MACRO(2) --> includes file2
BOOST_PP_LOCAL_MACRO(3) --> includes file3

Unfortunately the above does not work because of the #include GENERATE_FILE_NAME(n) in a macro which does not expand...

Is this even possible?

Comment:
I posted this question because I was wondering if this is even possible. I have solved my problem by including just one file which was generated from all files file1 file2 file3. I came across this, because sometimes one might generate big include file sequences (which should not be merged, just because of readability) and I was unsure how to include all those without writing explicitly all file names, so I thought about preprocessor loops, which is of course uglier then my solution so far :-), but its fancier :-)

1

There are 1 answers

2
AudioBubble On

This works with g++:

Having a directory preprocessor in the include path and this include_range.h:

#if !BOOST_PP_IS_ITERATING

#ifndef INCLUDE_RANGE_PREFIX
    #error Missing INCLUDE_RANGE_PREFIX
#endif
#ifndef INCLUDE_RANGE_MIN
    #error Missing INCLUDE_RANGE_MIN
#endif
#ifndef INCLUDE_RANGE_MAX
    #error Missing INCLUDE_RANGE_MAX
#endif

#include <boost/preprocessor/iteration/iterate.hpp>

#define BOOST_PP_ITERATION_PARAMS_1 (3, \
    (INCLUDE_RANGE_MIN, INCLUDE_RANGE_MAX, <preprocessor/include_range.h>))
#include BOOST_PP_ITERATE()

#else

#define INCLUDE_RANGE_PATH_SUFFIX(F, N) F##N
#define INCLUDE_RANGE_PATH(F, N) <INCLUDE_RANGE_PATH_SUFFIX(F, N)>
#include INCLUDE_RANGE_PATH(INCLUDE_RANGE_PREFIX, BOOST_PP_ITERATION())

#if BOOST_PP_ITERATION_DEPTH() == INCLUDE_RANGE_MAX - INCLUDE_RANGE_MIN + 1
    #undef INCLUDE_RANGE_PREFIX
    #undef INCLUDE_RANGE_MIN
    #undef INCLUDE_RANGE_MAX
#endif

#endif

You can include a range of files (file2, file3, file4):

#define INCLUDE_RANGE_PREFIX file
#define INCLUDE_RANGE_MIN 2
#define INCLUDE_RANGE_MAX 4
#include <preprocessor/include_range.h>

Limitation: The files are in the include path.