C-style programming
CPL.3
If you must use C for interfaces, use C++ in the calling code using such interfaces
Reason
C++ is more expressive than C and offers better support for many types of programming.
Example
For example, to use a 3rd party C library or C systems interface, define the low-level interface in the common subset of C and C++ for better type checking. Whenever possible encapsulate the low-level interface in an interface that follows the C++ guidelines (for better abstraction, memory safety, and resource safety) and use that C++ interface in C++ code.
Example
You can call C from C++:
// in C:
double sqrt(double);
// in C++:
extern "C" double sqrt(double);
sqrt(2);
Example
You can call C++ from C:
// in C:
X call_f(struct Y*, int);
// in C++:
extern "C" X call_f(Y* p, int i)
{
return p->f(i); // possibly a virtual function call
}
Enforcement
None needed
SF: Source files
Distinguish between declarations (used as interfaces) and definitions (used as implementations). Use header files to represent interfaces and to emphasize logical structure.
Source file rule summary:
- SF.1: Use a
.cppsuffix for code files and.hfor interface files if your project doesn't already follow another convention - SF.2: A header file must not contain object definitions or non-inline function definitions
- SF.3: Use header files for all declarations used in multiple source files
- SF.4: Include header files before other declarations in a file
- SF.5: A
.cppfile must include the header file(s) that defines its interface - SF.6: Use
using namespacedirectives for transition, for foundation libraries (such asstd), or within a local scope (only) - SF.7: Don't write
using namespaceat global scope in a header file - SF.8: Use
#includeguards for all header files - SF.9: Avoid cyclic dependencies among source files
- SF.10: Avoid dependencies on implicitly
#included names - SF.11: Header files should be self-contained
- SF.12: Prefer the quoted form of
#includefor files relative to the including file and the angle bracket form everywhere else - SF.13: Use portable header identifiers in
#includestatements