Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Preprocessor concatenation with variable [duplicate]

Possible Duplicate:
C preprocessor and concatenation

Is it possible to concatenate a C preprocessor with a variable name?

#define  WIDTH 32

int dataWIDTH;


// dataWIDTH should be interpreted as 'data32'

printf("%d",dataWIDTH);
like image 543
Jean Avatar asked Dec 17 '12 22:12

Jean


1 Answers

Your use case requires a double-unescaping; using the token pasting (##) operator by itself will just append the name of the preprocessor directive.

#define WIDTH 32

#define _MAKEDATA(n) data##n
#define MAKEDATA(n) _MAKEDATA(n)

int MAKEDATA(WIDTH) = 7;
int _MAKEDATA(WIDTH) = 8;

int main(int argc, char *argv[]) {
    printf("%d\n", data32);
    return 0;
}

yields

$ gcc -E foo.c 
int data32 = 7;
int dataWIDTH = 8;

int main(int argc, char *argv[]) {
    printf("%d\n", data32);
    return 0;
}
like image 112
user295691 Avatar answered Nov 11 '22 21:11

user295691