Bewlar
Bewlar

Reputation: 81

Understanding nested macro syntax in C

I'm trying to understand macros in C and need some help. I'm very new to coding and I appreciate any help on understanding.

  1. Does the syntax of macro definitions in C depend on your compiler or are there any C standard definitions that aren't specific to a compiler?
  2. The macros are executed by C preprocessing(CPP) correct? http://tigcc.ticalc.org/doc/cpp.html
  3. You can add to the macro definitions depending on the build environments you set correct?

  4. I'm trying to understand this code but I'm slightly confused. So the first line of code sets a function macro CAT which concatenates a and b right?

    The second line just creates a function QTE which takes in a name but I'm not quite sure what the single hash does in a macro...?

    The third line I'm only unsure because I've never seen a function with another function as its definition. Is it concatenating s_ and generic and then placing that value as the input to the function then using that function as a replacement for sel(generic)?

    In the fourth line class, _, and type are not defined but it will substitute the other three macro objects contained within the three functions of the fourth lines code correct?

    #define CAT(a,b)  a##b
    #define QTE(name) #name
    #define SEL(generic) CAT(s_,generic)
    #define export(class, generic, type) classMethod(class, SEL(generic), CAT(_, generic), type) ;
    

Upvotes: 0

Views: 1530

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753745

Converting comment into an answer.

  1. The basic syntax of macros is standard across all compilers.

  2. The macros can be interpreted by a separate C preprocessor program (traditionally called cpp), or as an integrated part of the main compiler. These days, the compilers normally use an integrated preprocessor rather than a standalone preprocessor, for a variety of complex reasons.

  3. Yes.

  4. Multiple parts:

    • The hash operator converts the argument to a string.
    • The SEL macro prefixes the symbol passed as an argument with s_.
    • The _ in the export is simply a 'letter'; class is a C++ keyword, but is used as a parameter name here (there aren't keywords when the preprocessor is running).
    • We've no idea what classMethod() does, but it is given a series of modified arguments.

Given:

export(Aaa, Bbb, Ccc)

you get the output from:

classMethod(Aaa, s_Bbb, _Bbb, Ccc);

The added semicolon in the macro definition for export is a bit dubious; normally, you'd invoke:

export(Aaa, Bbb, Ccc);   // Semicolon after invocation

and not include a semicolon in the macro definition.

Upvotes: 2

Related Questions