Search code examples
c++macrosincludec-preprocessor

Variable in include file c++


I am trying to include files in a cpp, but the filenames should be based on a variable.

In my case, the filenames should be filename_X.cpp where X ranges from 0 to 90 and filename is a predefined text, i.e. there is in total 90 includes statement. I would like to know if it is possible to

  1. Create a loop that includes 90 files

  2. Include using a variable filename

From searching through the internet, I have an approach to the point 2) as below:

#define FILENAME some_file_name

#define QUOTE(x) _QUOTE(x)
#define _QUOTE(x) #x

#define _CONCAT(x, y) x##_##y.cpp
#define CONCAT(x, y) _CONCAT(x, y)

#define _INCLUDE_FILE(x, y) (QUOTE(CONCAT(x, y)))
#define INCLUDE_FILE(x, y) _INCLUDE_FILE(x, y)

//#include INCLUDE_FILE(FILENAME, 0)

which works fine if I am calling a print function

printf(INCLUDE_FILE(FILENAME, 70));

It will print some_file_name_70.cpp .

However, when I try to use it in an include statement #include INCLUDE_FILE(FILENAME, 0), an error shows up as:

pred.cpp:22:10: error: expected "FILENAME" or <FILENAME>
#include INCLUDE_FILE(FILENAME, 0)
         ^
pred.cpp:20:28: note: expanded from macro 'INCLUDE_FILE'
#define INCLUDE_FILE(x, y) _INCLUDE_FILE(x, y)
                           ^
pred.cpp:19:29: note: expanded from macro '_INCLUDE_FILE'
#define _INCLUDE_FILE(x, y) (QUOTE(CONCAT(x, y)))
                            ^
1 error generated.

Does anyone know why does the error happen? Thank you very much!


Solution

  • That works for me, if I remove the parenthesis in the _INCLUDE_FILE macro:

    #define FILENAME t
    
    #define QUOTE(x) _QUOTE(x)
    #define _QUOTE(x) #x
    
    #define _CONCAT(x, y) x##y.h
    #define CONCAT(x, y) _CONCAT(x, y)
    
    #define _INCLUDE_FILE(x, y) QUOTE(CONCAT(x, y))
    #define INCLUDE_FILE(x, y) _INCLUDE_FILE(x, y)
    
    #include INCLUDE_FILE(FILENAME,1)
    
    int main (){
    }
    

    Always take care of parenthesis in macros...

    Note that you should not include .cpp files. That is not recommended, include only .h files. Except if you really know the weird thing your are doing.