微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C中的#define和#include顺序

我有以下代码,我用 gcc编译
#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&gt之前定义true时,为什么允许重新定义true? 更新: 这是stdbool.h.

前几行是

#ifndef _STDBOOL_H
#define _STDBOOL_H

#ifndef __cplusplus

#define bool    _Bool
#define true    1
#define false   0

这在余昊answer没有什么.

解决方法

虽然 Yu Hao给了 possible answer这个问题,但事情确实在这里不同了.

这很容易通过查看stdbool.h来实现,通过查看stdbool.h来了解,没有#ifdef … #endif围绕true的定义“守卫”.

此外,gcc只是简单地警告系统头文件中会出现哪些问题* 1.

使用gcc的选项-isystem使第一个例子表现得像第二个.

From the gcc manual:

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:系统头文件包含在<>括号.

原文地址:https://www.jb51.cc/c/115343.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐