I have some header file that was written for use in a C99 program. This header includes all the function definitions, and is not paired with a source file. I am including it in a C++ file.
My C++ compiler flags include -pedantic -std=c++11, which gives me various warnings in the header file such as “ISO C++ forbids compound literals”, and “ISO C++ forbids variable length arrays”. Obviously the C++ compiler is treating the C99 code as C++. Two questions:
- Is this a potential problem when trying to write code that will run correctly on various platforms using different compilers?
- What is a good way to resolve the warnings, and produce standard conforming code? I was thinking of making a precompiled header file using gcc, but don’t know enough about the process to be assured that I am not going to have unintended consequences from included a C precompiled header in a C++ source.
Thanks
To include a pure C header file(*) in a C++ project, you should wrap the include statement in an
extern "C"block:This is because C++ performs name mangling on all function names to make overloading work. C doesn’t use name mangling, so C++ parses C function signatures with name mangling.
Please note that
extern "C"doesn’t put the compiler into “C-mode” (there is no such mode but you might falsely think of this instruction as such), it doesn’t mangle the function names (+ changes the calling convention and forbids overloading; thanks for doomster for pointing these things out).However, it shouldn’t be a problem if you are including a header only (with inline implementations), since this name mangling will only be a problem when you link the C source file or library against your C++ project, since the function names are different in this case.
This being said, you should use the common subset of C and C++ for the header file, extract and compile the implementations of these functions separately with a C compiler, not C++. Then, you (hopefully) can link both parts together. A lot of C libraries already have headers which are compatible with C++, so this is a common procedure.
(*): Some header files are already made to be compatible with both languages C and C++ by using the common subset of language features plus wrapping everything in a conditional
extern "C"block. For such headers, you should not use this method, but only for the ones which don’t have such a block in it.