Getting const char with the preprocessor syntax
-
02-07-2021 - |
Question
To correct for typos, and to add the issue I'm having which I forgot to mention, here is the macro:
#define SUFFIX .new
#define STR(x) #x
#define GENFILE(name,suff) STR(timings/name suff)
GENFILE(test1, SUFFIX)
The above code generates timings/test1 .new
and if only I didn't have that extra space, I would have what I want, how do I get around that?
Solution
There is no single token (call it "word" if you like) /test1
. /test1
is the division operator /
followed by the identifier test1
, and they cannot be added together. Luckily, you don't need to. If they appear together without any intervening spaces, and you stringize it, no space gets inserted. So just remove the ##
.
Also make sure your macro parameter name matches what you use in the definition. testname
and name
are not the same.
#define STR(x) #x
#define FILE(testname) STR(timings/testname)
Update:
Since you've edited your question, the above is no longer a complete answer.
You get the space because you included a space in the macro definition, and you need to rewrite your macro definition to not include a space. One way to do it is with an extra macro like this:
#define SUFFIX .new
#define STR(x) STR_(x)
#define STR_(x) #x
#define ID(x) x
#define GENFILE(name,suff) STR(timings/ID(name)suff)
GENFILE(test1, SUFFIX) // expands to "timings/test1.new"
Note that the STR
macro now needs an extra helper macro too, to allow ID
to get expanded before including it in the string.
OTHER TIPS
Simpler: Just say #define GENFILE(name) STR(timings/name)
.
The slash separates preprocessor tokens, so GENFILE(test1)
becomes STR(timings/test1)
which is stringified as a whole.
(Now you can say #include GENFILE(myheader)
.)
Alternatively, you can say #define GENFILE(name) STR(timings/) #name
, but that would result in two concatenated strings "timings/" "test1"
. Note quite as pretty, and as @hvd observes rightly, string concatenation can't be used inside #include
directives.