【问题标题】:Gcc preprocessor and pastingGcc 预处理器和粘贴
【发布时间】:2014-06-14 12:03:18
【问题描述】:

前几天我在stackoverflow上找到了这个sn-p(谢谢):

#define PLATFORM 3
#define PASTER(x,y) x ## _ ## y
#define EVALUATOR(x,y)  PASTER(x,y)
#define PLATFORMSPECIFIC(fun) EVALUATOR(fun, PLATFORM)

extern void PLATFORMSPECIFIC(somefunc)(char *x);

用gcc -E编译,结果:

# 1 "xx.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "xx.c"





extern void somefunc_3(char *x);

但是:

#define PLATFORM linux
#define PASTER(x,y) x ## _ ## y
#define EVALUATOR(x,y)  PASTER(x,y)
#define PLATFORMSPECIFIC(fun) EVALUATOR(fun, PLATFORM)

extern void PLATFORMSPECIFIC(somefunc)(char *x);

结果:

# 1 "xx.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "xx.c"





extern void somefunc_1(char *x);

我该怎么做才能让这个返回 'somefunc_linux' ?顺便说一句,Clang 似乎做得对。

【问题讨论】:

  • 还要说明你的编译器版本。我使用 clang 和 gcc 得到相同的结果 - 因为两个编译器都预定义了 #define linux 1
  • 啊.. 好电话。我没有检查 linux 是否是预定义的。
  • 我以为在Linux上,它只是'linux',两端有两个下划线。我的错。
  • 查看stackoverflow.com/questions/19210935/… - 对此进行了大量讨论。
  • 我认为更有理由有一个特殊的标记来表示“评估这个” - 比如,一个美元符号或其他东西。它适用于贝壳......

标签: c++ c gcc


【解决方案1】:

如果您想使用 linux 作为名称,可以更改编译器选项以取消定义它:

gcc -Ulinux

或符合标准:

gcc -std=c90 -pedantic ... # or -std=c89 or -ansi
gcc -std=c99 -pedantic
gcc -std=c11 -pedantic

在此处查看有关原因的更多讨论:Why does the C preprocessor interpret the word "linux" as the constant "1"?

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 2014-09-13
    • 2011-04-24
    • 2015-11-22
    • 1970-01-01
    • 2012-07-13
    • 2021-11-27
    相关资源
    最近更新 更多