In a C++ project, including .h files of C source files will cause many errors because of different standards between C and C++.
How to use C source files in a C++ project (or in main.cpp)?
In a C++ project, including .h files of C source files will cause many
Share
For the maximum reliability:
Make sure that the C headers are either themselves aware of C++ or that the C++ code includes the C headers inside an
extern "C" { ... }block.Either (C header file
cheader.h):or (C++ source code):
Modern C style is very close to the common subset of the C and C++ languages. However, arbitrary C code is not C++ code for any of a very large number of reasons, and simply calling the C source files C++ source files (by changing the extension, or simply by compiling with the C++ compiler) is not guaranteed to be successful. In general, it is easier to compile C as C and C++ as C++ and then link the resulting object files with the C++ compiler (to ensure the correct support libraries are invoked).
However, if the MSVC compiler is saying that programs using MFC have to be written solely in C++ (MFC requires C++ compilation (use a .cpp suffix) is the reported error), then you may have no choice but to ensure that your C code is compilable as C++ code. That means you’ll have to cast the return values from
malloc()et al; you have to worry about other places where you do not use a cast to convert avoid *into some other pointer type; you have to worry aboutsizeof('a') == 4in C andsizeof('a') == 1in C++; you have to ensure that every function is declared before it is used; you have to ensure your C code does not use any C++ keywords (typename,classin particular; alsoinlinesometimes — but the complete list is quite large).In some circles, you’d have to worry about the use of features in C99 that are not in C++2003 or C++2011, such as flexible array members, designated initializers, compound literals, variable-length arrays, and so on. However, if the C code is for MSVC, then that probably isn’t going to be a problem; those features are not supported by the MSVC C compiler (it only supports C89, not C99).
FWIW: I have a script to hunt down C++ keywords. It contains the following comment:
The
(1)suffixes is a footnote at CPP Reference:(1)— meaning changed in C++11