C++核心准则SF.5: .cpp文件必须包含定义它接口的.h文件

时间:2022-07-26
本文章向大家介绍C++核心准则SF.5: .cpp文件必须包含定义它接口的.h文件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

SF.5: A .cpp file must include the .h file(s) that defines its interface

SF.5: .cpp文件必须包含定义它接口的.h文件

Reason(原因)

This enables the compiler to do an early consistency check.

这样可以让编译器尽早进行一致性检查。

Example, bad(反面示例)

// foo.h:
void foo(int);
int bar(long);SF.5: .cpp文件必须包含定义它接口的.h文件
int foobar(int);

// foo.cpp:
void foo(int) { /* ... */ }
int bar(double) { /* ... */ }
double foobar(int);

The errors will not be caught until link time for a program calling bar or foobar.

如果有程序调用bar或foobar,直到链接时这个错误才能被发现。

Example(示例)

// foo.h:
void foo(int);
int bar(long);
int foobar(int);

// foo.cpp:
#include <foo.h>

void foo(int) { /* ... */ }
int bar(double) { /* ... */ }
double foobar(int);   // error: wrong return type

The return-type error for foobar is now caught immediately when foo.cpp is compiled. The argument-type error for bar cannot be caught until link time because of the possibility of overloading, but systematic use of .h files increases the likelihood that it is caught earlier by the programmer.

当foo.cpp被编译时,foobar的返回值类型错误可以立即被发现。由于可能存在的重载,直到链接时,bar的参数类型错误才能被发现。但是系统性地使用.h文件会提高错误被程序员早期发现的可能性。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf5-a-cpp-file-must-include-the-h-files-that-defines-its-interface