I'm trying to use the stdbool.h library file in a C program. When I try to compile, however, an error message appears saying intellisense cannot open source file stdbool.h.
Can anyone please advise how I would get visual studio to recognise this? Is this header file even valid? I'm reading a book on learning C programming.
typedef int bool;
#define false 0
#define true 1
works just fine. The Windows headers do the same thing. There's absolutely no reason to fret about the "wasted" memory expended by storing a two-bit value in an int
.
As Alexandre mentioned in a comment, Microsoft's C compiler (bundled with Visual Studio) doesn't support C99 and likely isn't going to. It's unfortunate, because stdbool.h
and many other far more useful features are supported in C99, but not in Visual Studio. It's stuck in the past, supporting only the older standard known as C89. I'm surprised you haven't run into a problem trying to define variables somewhere other than the beginning of a block. That bites me every time I write C code in VS.
One possible workaround is to configure Visual Studio to compile the code as C++. Then almost everything you read in the C99 book will work without the compiler choking. In C++, the type bool
is built in (although it is a 1-byte type in C++ mode, rather than a 4-byte type like in C mode). To make this change, you can edit your project's compilation settings within the IDE, or you can simply rename the file to have a cpp
extension (rather than c
). VS will automatically set the compilation mode accordingly.
Modern versions of Visual Studio (2013 and later) offer improved support for C99, but it is still not complete. Honestly, the better solution if you're trying to learn C (and therefore C99 nowadays) is to just pick up a different compiler. MinGW is a good option if you're running on Windows. Lots of people like the Code::Blocks IDE
Create your own file to replace stdbool.h that looks like this:
#pragma once
#define false 0
#define true 1
#define bool int
In Visual Studio 2010 I had an issue using typedef int bool;
as suggested elsewhere. IntelliSense complained about an "invalid combination of type specifiers." It seems that the name "bool" is still special, even though it's not defined.
Just as a warning, on x64 platforms, VS2017 (I'm not sure about previous versions) defines bool
as a value of 1 byte on C++ (e.g. a char
). So this
typedef int bool;
could be really dangerous if you use it as an int
(4 bytes) in C files and as a native bool
in C++ (1 byte) (e.g. a struct
in a .h
might have different sizes depending if you compile it with C or C++).