gcc:-DVAR = -linux在linux上没有像预期的那样工作

我有以下的C程序:

test.c的

#include <stdio.h> #define DEF0(v) #v #define DEF(v) DEF0(v) int main() { printf("RUNNING... %s\n", DEF(VAR)); } 

汇编

gcc -DVAR=-linux test.c

运行

./a.out

RUNNING... -1

Asm输出

  .file "test.c" .section .rodata.str1.1,"aMS",@progbits,1 .LC0: .string "-1" .LC1: .string "RUNNING... %s\n" .text .p2align 4,,15 .globl main .type main, @function main: .LFB11: .cfi_startproc movl $.LC0, %esi movl $.LC1, %edi xorl %eax, %eax jmp printf .cfi_endproc .LFE11: .size main, .-main .ident "GCC: (GNU) 4.4.7 20120313 (Red Hat 4.4.7-4)" .section .note.GNU-stack,"",@progbits 

-linu-linuxx不会导致这样的问题,但-linux/的确。 周围用引号-DVAR="-linux"没有帮助。

在gcc 6和7上也可以看到问题。在cygwin上,所有东西都可以工作。 我不知道这是一个错误还是我做错了什么。

在编译你的目标文件时,你可以用-undef来禁止系统或gcc特定宏的定义:

 gcc -undef -c -DVAR=-linux test.c gcc test.o -o test 

那么你的宏应该像你期望的那样工作。 但是请注意,您不能使用这些预定义宏中的任何一个,那么您应该只将它用在您必须使用的那些对象文件上。