Reputation: 2212
I have such simple code:
#define THE_MACRO World
void Hello##THE_MACRO()
{
}
By pre-process it with clang++ code.cpp -E
I get such result:
# 1 "code.cpp"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 326 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "code.cpp" 2
void Hello##World()
{
}
Please notice the ##
still remain in the code and will lead a compile error:
code.cpp:3:6: error: variable has incomplete type 'void'
void Hello##THE_MACRO()
^
code.cpp:3:11: error: expected ';' after top level declarator
void Hello##THE_MACRO()
^
;
I can't figure what's wrong with the code. Should provide any arguments more for clang?
Upvotes: 0
Views: 81
Reputation: 2006
The ## operator must appear inside of a macro. Macros are processed in the order that they are available, but if the result of one macro produces a new macro, that will be processed as well. Thus, sometimes you want to have one macro call another that actually implements the functionality (and is defined later) to make sure the arguments are processed correctly.
So, if you want to build your set of macros, you can do:
#include <iostream>
#define MERGE(A,B) MERGE_IMPL(A,B)
#define MERGE_IMPL(A,B) A ## B
#define XXX Hello
#define YYY World
void MERGE(XXX, YYY)() {
std::cout << "Yay!" << std::endl;
}
int main() {
HelloWorld();
}
The above program should run, correctly translating the macros, allowing the HelloWorld() function to be defined and called successfully from main.
Upvotes: 1
Reputation: 4189
Edit your macro as follows:
#define THE_MACRO(x) x ## World()
And then:
void THE_MACRO(Hello)
{
}
As @bmargulies points out, ##
is available in a macro context.
Upvotes: 1