0
点赞
收藏
分享

微信扫一扫

【c语言 gcc9.1.0环境下编译报错】error: ‘true’ undeclared (first use in this function)


问题

网上验证一个单链表是否有环的c语言demo,放到​​gcc9.1.0​​​的环境下编译,发现编译报错:
​​​error: ‘true’ undeclared (first use in this function)​

分析

发现是demo里使用到的​​true​​​和​​flase​​​编译报错了,原来gcc9.1.0下​​bool关键字​​​还未支持。
深入分析后发现,原来C语言(C99之前)中没有​​​bool关键字​​​。在C语言编程时,我们都是使用​​BOOL​​​,但​​BOOL​​​不是内置类型,一般都是通过​​typedef​​​或者​​宏​​来定义的,通常都会被定义成int类型。

typedef int BOOL;

  #define TRUE 1

  #define FALSE 0

后来的C++出现了​​内置类型bool​​​,值为true(真)和false(假)。为了与C++兼容,C99标准新增的头文件​​stdbool.h​​​头文件中引入​​bool关键字​​。

//
// stdbool.h
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The C Standard Library <stdbool.h> header.
//
#ifndef _STDBOOL
#define _STDBOOL

#define __bool_true_false_are_defined 1

#ifndef __cplusplus

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

#endif /* __cplusplus */

#endif /* _STDBOOL */

/*
* Copyright (c) 1992-2010 by P.J. Plauger. ALL RIGHTS RESERVED.
* Consult your license regarding permissions and restrictions.
V5.30:0009 */

解决

法1:

由于我是单独跑demo验证的,所以我就写了一个宏定义来保证编译通过就行了了。

typedef enum __bool 
{
false = 0,
true = 1
} bool;

法2:

在源文件中包含​​stdbool.h​​头文件即可。

#include <stdbool.h>

番外

针对C99标准( ISO/IEC 9899: 1999),毫不夸张地说,即便到目前为止,很少有C语言编译器是完整支持 C99 的。像主流的 GCC 以及 Clang 编译器都能支持高达90%以上,而微软的 Visual Studio 2015 中的C编译器只能支持到 70% 左右。

所以建议大家在进行C/C++混合编程时,一定要注意代码兼容性。特别是注意一些编程语言特有的关键字与语法等,不能混为一谈,尽量避免不必要的麻烦。

引经据典

​​http://c.biancheng.net/view/143.html​​


举报

相关推荐

0 条评论