C++核心准则SF.3:使用.h文件管理所有在多个源文件中使用的声明

时间:2022-07-26
本文章向大家介绍C++核心准则SF.3:使用.h文件管理所有在多个源文件中使用的声明,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

SF.3: Use .h files for all declarations used in multiple source files

SF.3:使用.h文件管理所有在多个源文件中使用的声明

Reason(原因)

Maintainability. Readability.

维护性。可读性。

Example, bad(反面示例)

// bar.cpp:
void bar() { cout << "barn"; }

// foo.cpp:
extern void bar();
void foo() { bar(); }

A maintainer of bar cannot find all declarations of bar if its type needs changing. The user of bar cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker.

如果需要修改bar的类型,维护者无法找到bar的所有声明。bar的用户无法知道所用的接口是否完全和正确。

Enforcement(实施建议)

  • Flag declarations of entities in other source files not placed in a .h.
  • 标记实体的定义没有放在.h文件中而放在其他源文件中的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf3-use-h-files-for-all-declarations-used-in-multiple-source-files