I have the following define:
#define MY_CLASS MyClass
I'm trying to make a macro that will use MY_CLASS to expand to:
#include "MyClass.h"
Something like (according to this answer):
#define MY_CLASS MyClass
#define FILE_EXT h
#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define APP_BUILD M_CONC(MY_CLASS, M_CONC(.,FILE_EXT))
#include APP_BUILD
That one doesn't work though... I get these 3 errors:
Expected "FILENAME" or <FILENAME>
Pasting formed '.h', an invalid preprocessing token
Pasting formed 'MyClass.', an invalid preprocessing token
Is it possible to do it somehow?
CodePudding user response:
I was referred to this post in the comments (thanks @sj95126) which I originally missed. It didn't work as-is but I was able to deduce the right answer from it rather quickly...
This works:
#define MY_CLASS MyClass
#define EMPTY
#define MACRO1(x) #x
#define MACRO2(x, y) MACRO1(x##y.h)
#define MACRO3(x, y) MACRO2(x, y)
#include MACRO3(EMPTY, MY_CLASS)
If there's a more elegant / quicker (maybe 1 less macro definition?) solution I would be happy accept a different answer.
CodePudding user response:
As to your Question: If there's a more elegant / quicker (maybe 1 less macro definition?) solution
#define STRINGIFY(X) #X
#define FILE_H(X) STRINGIFY(X.h)
//usage:
#define MY_CLASS MyClass
#include FILE_H(MY_CLASS)
//expands to: #include "MyCLass.h"
//or
#define ANOTHER_CLASS AnotherClass
#include FILE_H(ANOTHER_CLASS)
//expands to: #include "AnotherClass.h"
Well, if you need concatenation, then you have to add two extra lines:
#define CONCAT(A,B) CONCAT_(A,B)
#define CONCAT_(A,B) A##B
//could be extended like this:
//#define CONCAT3(A,B,C) CONCAT(CONCAT(A,B),C)
//...