Check if bool is defined in mixed C/C++

前端 未结 4 916
甜味超标
甜味超标 2021-02-05 19:51

So I\'m having issues with some code that I\'ve inherited. This code was building fine in a C-only environment, but now I need to use C++ to call this code. The header p

相关标签:
4条回答
  • 2021-02-05 20:35

    You can use C99's bool:

    #ifndef __cplusplus
    #include <stdbool.h>
    #endif
    
    bool myBoolean; // bool is declared as either C99's _Bool, or C++'s bool data type.
    

    Why should you use this?

    For compatibility with other C99 code. _Bool is commonly used in C99 Code, and is very useful. It also grants you the ability to have a boolean datatype without the need to typedef a lot of stuff, as behind the scenes, _Bool is a datatype defined by the compiler.

    0 讨论(0)
  • 2021-02-05 20:36

    Because bool is a basic type in C++ (but not in C), and can't be redefined.

    You can surround your code with

    #ifndef __cplusplus
    typedef unsigned char bool;
    static const bool False = 0;
    static const bool True = 1;
    #endif
    
    0 讨论(0)
  • 2021-02-05 20:39

    I had this "'char' followed by 'bool' is illegal" problem in VS also. The problem for me was I did not end my class declaration with a semi-colon- which I was not expecting to be the issue as this was in the header file and the problem was coming up in the cpp file! eg:

    class myClass
    {
    
    }; // <-- put the semi colon !!
    
    0 讨论(0)
  • 2021-02-05 20:54

    You should use the __cplusplus macro:

    #ifndef __cplusplus
    #ifndef _BOOL
    typedef unsigned char bool;
    static const bool False = 0;
    static const bool True = 1;
    #endif
    #endif 
    

    Check out this link to the C++ FAQ for further details.

    0 讨论(0)
提交回复
热议问题