How to escape an underscore in a C preprocessor token?
-
02-07-2019 - |
Question
The following snippet is supposed to take the value of PROJECT (defined in the Makefile) and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR
I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?
#define PROJECT classifier
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
#include PROJECTINCSTR
Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.
Solution
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define SMASH(x,y) x##y
#define MAKEINC(x) SMASH(x,_ir.h)
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
OTHER TIPS
This works for me:
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC(x) MAKEINC(x)
#define PROJECTINCSTR MAKESTR(PROJECTINC(PROJECT))
#include PROJECTINCSTR
That barebone example works with gcc (v4.1.2) and tries to include "PROJECT_ir.h"