#include<stdio.h> #include<stdbool.h> #define true 9 int main() { printf("TRUE = %d\n",true); return 0; }
我得到错误
test.c:3:0: warning: "true" redefined [enabled by default] In file included from test.c:2:0: /usr/lib/gcc/x86_64-linux-gnu/4.7/include/stdbool.h:34:0: note: this is the location of the prevIoUs definition
但是当我改变代码的时候
#include<stdio.h> #define true 9 #include<stdbool.h> int main() { printf("TRUE = %d\n",true); return 0; }
输出:
TRUE = 1
题:
我明白第一种情况的错误的原因,但在第二种情况下,当我在#include< stdbool.h>之前定义true时,为什么允许重新定义true? 更新: 这是stdbool.h.
前几行是
#ifndef _STDBOOL_H #define _STDBOOL_H #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0
这在余昊answer没有什么.
解决方法
这很容易通过查看stdbool.h来实现,通过查看stdbool.h来了解,没有#ifdef … #endif围绕true的定义“守卫”.
此外,gcc只是简单地警告系统头文件中会出现哪些问题* 1.
使用gcc的选项-isystem使第一个例子表现得像第二个.
The header files declaring interfaces to the operating system and runtime libraries often cannot be written in strictly conforming C. Therefore,GCC gives code found in system headers special treatment. All warnings,other than those generated by ‘#warning’ (see Diagnostics),are suppressed while GCC is processing a system header. Macros defined in a system header are immune to a few warnings wherever they are expanded. This immunity is granted on an ad-hoc basis,when we find that a warning generates lots of false positives because of code in macros defined in system headers.
[…]
The -isystem command line option adds its argument to the list of directories to search for headers,just like -I. Any headers found in that directory will be considered system headers.
* 1:系统头文件包含在<>括号.