1

I'm trying to include mongoose web server, which is written in C, and write the rest of the code in C++. When compiling I get the error: redeclaration of C++ built-in type 'bool' in the mongoose header file in Code Blocks

#include <iostream>
#include "mongoose.h"

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

I enclosed the mongoose header in

#ifdef __cplusplus
    extern "C"{
#endif 
// header content
#ifdef __cplusplus
    }
#endif

and I'm still getting the same error, at #include winsock2.h

2 Answers2

2

C and C++ are different languages that share a common subset. You can compile most C declarations with a C++ compiler by putting them in a section specifying C linkage, as you show, but that follows from the sublanguage of C declarations being almost entirely within the shared subset of C and C++.

C++ has both more declarational features and more constraints than C does, however. In particular, the fact that it provides bool as a built-in type places a constraint that that identifier cannot be redeclared as a typedef name. C, on the other hand, has a standard header that defines exactly such a typedef, and it is not so uncommon for people to roll their own, too. Such typedefs will be rejected by a C++ compiler, C linkage notwithstanding.

If the C project is not already built with a mind toward providing for use by C++ programs, and simply wrapping the header inclusion in a C linkage block does not suffice, then you simply cannot use that library's header as-is. Your options are either to modify it or to provide an alternative. You might even need to provide a few wrapper functions, written in C, to serve as an interface with your C++ program. Details depend on the library you're trying to use.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

If this is your only issue, then you could add #define bool C_INT_BOOL near your extern "C", then #undef bool near the }
In your cpp file I would write:

extern "C"{
#define bool C_INT_BOOL
#include "mongoose.h"
#undef bool
}

This allows the "C" interface to see the int parameter type, but shouldn't interfere with your c++ use of bool.

But I doubt this will be your only issue, in which case you will probaby quickly realise that adding an interface function layer is the safest way to go.

Gem Taylor
  • 5,381
  • 1
  • 9
  • 27