Reputation: 117
I came across this code that I could not understand and could not find the answer anywhere:
#define CMD_MAP(F)
F(READ, NETFN_SE, 0x01, 1) \
F(WRITE, NETFN_SE, 0x02, 8)
typedef enum {
#define CMD_ENUM(A, B, C, D) A ,
CMD_MAP(CMD_ENUM)
} cmd_t;
What's the rule for syntax here? CMD_MAP(F) means passing those arguments to function F?
Upvotes: 0
Views: 897
Reputation: 2273
Macros are processed before the actual compiling starts. They are just rules how the preprocessor should edit the text (code).
CMD_MAP(foo)
expands to foo(READ, NETFN_SE, 0x01, 1) foo(WRITE, NETFN_SE, 0x02, 8)
which is then compiled.
The backslash just tells the preprocessor that the macro continues in the next line.
/Edit: Macro is written with a 'c' instead of 'k' like in Germany ;)
/Edit2: Basic macro-function guide
The basic syntax for a makro is this one:
#define MAKRO_NAME(argument1, argument2, ...) <definition of replacement-text>
Take this simple example:
#define GET_A(val) val.a
The principle behind this is, that when "calling" the macro, the val in 'val.a' gets replaced by whatever you put inside the parenthesis. So if I write the following in my code: int x = GET_A(someObject);
it would be expanded (pre-compiled) to: int x = someObject.a;
and the following:
#define GET_SOMEVAL(obj, val) obj.val
//...
int x = GET_SOMEVAL(myObject, myVal);
would be expanded to: int x = myObject.myVal;
As you see these are just replacements on a textual basis, the preprocessor does not know anything about the grammar or syntax of C++. Macros don't have to do anything with function calls or whatever, they just work by replacing text. There is some more (dark) magic in macros, but this should do it.
Back to your question: The preprocessor just replaces 'F' with whatever you put inside the paranthesis when writing CMD_MAP(this here replaces F)
Upvotes: 1