C Preprocessor concatenation with variable
10,363
Solution 1
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;
}
Solution 2
There's a token pasting operator called ##, read about it for example here:
http://msdn.microsoft.com/en-us/library/09dwwt6y(v=vs.80).aspx
Author by
Jean
Full time Plumber. I speak Malayalam. ആന പോകുന്ന പൂമരത്തിന്റെ ചോടെപോകുന്നതാരെടാ.. ആരാനുമല്ല കൂരാനുമല്ല കുഞ്ഞുണ്ണിമാഷും കുട്ട്യോളും - കുഞ്ഞുണ്ണിമാഷ് 7 out of 10 internet users don't know that Ad free browsing is possible https://adblockplus.org/
Updated on June 09, 2022Comments
-
Jean almost 2 years
Possible Duplicate:
C preprocessor and concatenationIs 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);
-
user295691 over 11 yearsAlso, see stackoverflow.com/questions/1489932/… for an excellent discussion of the double-pasting "trick"
-
user295691 over 11 yearsThe preprocessor expands this to
printf("%d", data##32)
, which yields a compiler error. My understanding is that token pasting only works inside of macros. -
Per Ersson over 11 yearsThat example was added by another user, the provided link shows how to use token-pasting from within a macro.