Reputation: 3765
Here is what I am thinking.
#define prefix_1 1
#define prefix_2 2
#define prefix_3 3
And I want to define a macro using the prefixes above — like macro macro_prefix_1
macro_prefix_2
— and I expect them to turn into macro_1
macro_2
, etc. Just like the code below
#define macro_##prefix_1 I_am_macro_1
#define macro_##prefix_2 I_am_macro_2
Is this possible?
Upvotes: 5
Views: 456
Reputation: 173
Unfortunately, what you are trying to do is impossible. The (##) directive is impossible to use within a macro declaration. It is only possible to use it within the definition as such.
#define glue(a,b) a ## b
glue(c,out) << "test";
Example borrowed from cplusplus.com
Below, I have written an example of what you want to do.
#include <stdio.h>
#define prefix_1 1
#define prefix_2 2
#define prefix_3 3
#define macro_##prefix_1 "macro_1"
#define macro_##prefix_2 "macro_2"
#define macro_##prefix_3 "macro_3"
int main(){
printf("%s\n%s\n%s\n", macro_prefix_1, macro_prefix_2, macro_prefix_3);
return 0;
}
When you try to compile the above code you will get this build log.
||=== Build: Debug in file_test (compiler: GNU GCC Compiler) ===|
main.cpp|7|warning: missing whitespace after the macro name [enabled by default]|
main.cpp|7|error: '##' cannot appear at either end of a macro expansion|
main.cpp|8|warning: missing whitespace after the macro name [enabled by default]|
main.cpp|8|error: '##' cannot appear at either end of a macro expansion|
main.cpp|9|warning: missing whitespace after the macro name [enabled by default]|
main.cpp|9|error: '##' cannot appear at either end of a macro expansion|
main.cpp||In function 'int main()':|
main.cpp|13|error: 'macro_prefix_1' was not declared in this scope|
main.cpp|13|error: 'macro_prefix_2' was not declared in this scope|
main.cpp|13|error: 'macro_prefix_3' was not declared in this scope|
||=== Build failed: 6 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
So if you want to be able to have macro's you will just have to add the prefix normally. Luckily you were basically already doing this, but adding "##". Hope this helped.
Upvotes: 2