简体   繁体   中英

Why does this C stringification macro corrupt whilst expanding?

#include <stdio.h>

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST one-of-a-linux

int main() {
  printf(EXPAND_AND_QUOTE(TEST)"\n");
}

I get:

one-of-a-1

rather than

one-of-a-linux

Note that "linux" becomes "1" - ie the digit one

显然在某处有#define linux 1 (或-Dlinux=1 )。

On my Linux box:

$ gcc -dM -E - < /dev/null | grep 'linux\|unix'
#define __unix__ 1
#define __linux 1
#define __unix 1
#define __linux__ 1
#define __gnu_linux__ 1
#define unix 1
#define linux 1
$

Note the value of unix being 1 on unix platforms has been used in an IOCCC entry. Winner of the "Best One Liner" in 1987.

http://www.ioccc.org/years.html#1987_korn

The code was:

    main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}
#undef linux
#define TEST one-of-a-linux

You have a #define for linux to 1 somewhere in your code. The following works fine!

#include <stdio.h>

#undef linux

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST one-of-a-linux

int main(void) 
{
    printf(EXPAND_AND_QUOTE(TEST)"\n");
    return 0;
}

Output:

/*
$ gcc mm.c 
$ ./a.out 
one-of-a-linux
$ 
*/

Note:

#define TEST 1linux
#define TEST linux1

prints the expected answers appropriately!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM