C++核心准则SF.1:如果你的项目没有正在遵从的其他习惯,为代码文件使用.cpp后缀,为接口文件使用.h后缀

时间:2022-07-26
本文章向大家介绍C++核心准则SF.1:如果你的项目没有正在遵从的其他习惯,为代码文件使用.cpp后缀,为接口文件使用.h后缀,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

SF.1: Use a .cpp suffix for code files and .h for interface files if your project doesn't already follow another convention

SF.1:如果你的项目没有正在遵从的其他习惯,为代码文件使用.cpp后缀,为接口文件使用.h后缀

Reason(原因)

It's a longstanding convention. But consistency is more important, so if your project uses something else, follow that.

这是长期以来的习惯。但是连贯性更加重要,因此如果你的项目已有其他传统,遵守它。

Note(注意)

This convention reflects a common use pattern: Headers are more often shared with C to compile as both C++ and C, which typically uses .h, and it's easier to name all headers .h instead of having different extensions for just those headers that are intended to be shared with C. On the other hand, implementation files are rarely shared with C and so should typically be distinguished from .c files, so it's normally best to name all C++ implementation files something else (such as .cpp).

这个习惯反映一个常见的使用模式:头文件更多地和C代码一起被分享并且和C++或C代码一起编译,它们通常使用.h后缀。使用.h为所有的头文件命名比较容易,而不是只为试图和C代码一起分享的头文件使用.h后缀。另一方面,(C++,译者注)实现文件极少和C代码一起分享,通常需要和.c文件区分开来,因此一般最好为所有的C++实现代码使用其他后缀(例如.cpp)。

The specific names .h and .cpp are not required (just recommended as a default) and other names are in widespread use. Examples are .hh, .C, and .cxx. Use such names equivalently. In this document, we refer to .h and .cpp as a shorthand for header and implementation files, even though the actual extension might be different.

特定的.h和.cpp后缀不是必须的(只是作为默认值被推荐),其他的名称也已经被广泛使用。例如.hh,.C,和.cxx等。使用这些名称同样可以。在本文档中,我们更加推荐.h和.cpp作为头文件和实现文件的简略命名方式,哪怕它们的实际上使用了其他的后缀。

Your IDE (if you use one) might have strong opinions about suffixes.

你的IDE(如果你在使用的话)有可能存在有关后缀的强烈选项。

Example(示例)

// foo.h:
extern int a;   // a declaration
extern void foo();

// foo.cpp:
int a;   // a definition
void foo() { ++a; }

foo.h provides the interface to foo.cpp. Global variables are best avoided.

foo.h提供foo.cpp的接口。最好避免全局变量。

Example, bad(反面示例)

// foo.h:
int a;   // a definition
void foo() { ++a; }

#include <foo.h> twice in a program and you get a linker error for two one-definition-rule violations.

在一个程序中两次#include<foo.h>会引发2个违反一次定义规则的链接错误。

Enforcement(实施建议)

  • Flag non-conventional file names.
  • 标记不存在文件命名习惯的情况。
  • Check that .h and .cpp (and equivalents) follow the rules below.
  • 检查.h文件和.cpp文件(或其他等价习惯)是否遵守下面的规则。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf1-use-a-cpp-suffix-for-code-files-and-h-for-interface-files-if-your-project-doesnt-already-follow-another-convention