What issues can I expect compiling C code with a C++ compiler?

I’ve done something like this once. The main source of problems was that C++ is more strict about types, as you suspected. You’ll have to add casts where void* are mixed with pointers of other types. Like allocating memory:

Foo *foo;
foo = malloc(sizeof(*foo));

The above is typical C code, but it’ll need a cast in C++:

Foo *foo;
foo = (Foo*)malloc(sizeof(*foo));

There are new reserved words in C++, such as “class”, “and”, “bool”, “catch”, “delete”, “explicit”, “mutable”, “namespace”, “new”, “operator”, “or”, “private”, “protected”, “friend”, etc. These cannot be used as variable names, for example.

The above are probably the most common problems when you compile old C code with a C++ compiler. For a complete list of incompatibilities, see Incompatibilities Between ISO C and ISO C++.

You also ask about name mangling. In absence of extern “C” wrappers, the C++ compiler will mangle the symbols. It’s not a problem as long as you use only a C++ compiler, and don’t rely on dlsym() or something like that to pull symbols from libraries.

Leave a Comment