0

In the following piece of code in the functional mock-up interface header file

#define fmiPaste(a,b)     a ## b
#define fmiPasteB(a,b)    fmiPaste(a,b)
#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)

Why are nested macros being used in the first place? Why not just

#define fmiPasteB(a,b)    a ## b
#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)

?

yaska
  • 225
  • 3
  • 7

1 Answers1

0

It has to do with how C expands macros.

If you do not have the nested macro, then the literal symbol that is passed into fmiFullName will be stringified and used for concatenation, instead the expansion of the symbol.

Consider the sample program below:

#include <stdio.h>

#define MODEL_IDENTIFIER Prefix

#define fmiPaste(a,b)     a ## b
#define fmiPasteB(a,b)    fmiPaste(a,b)
#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)


int main(){
    int Prefix1 = 2;
    int Prefix2 = 3;
    printf("%d\n", fmiFullName(1));
    printf("%d\n", fmiFullName(2));


#undef fmiPasteB
#undef fmiFullName


#define fmiPasteB(a,b)    a ## b
#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)

    int MODEL_IDENTIFIER1 = 100;
    int MODEL_IDENTIFIER2 = 1000;
    printf("%d\n", fmiFullName(1));
    printf("%d\n", fmiFullName(2));
}

Output:

int MODEL_IDENTIFIER1 = 100;
int MODEL_IDENTIFIER2 = 1000;
printf("%d\n", fmiFullName(1));
printf("%d\n", fmiFullName(2));
merlin2011
  • 71,677
  • 44
  • 195
  • 329