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?

Was it helpful?

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 re­sult in two con­ca­te­na­ted strings "timings/" "test1". Note quite as pretty, and as @hvd observes rightly, string con­cate­na­tion can't be used inside #include directives.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top