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

面向对象思考

共 2844字,需浏览 6分钟

 · 2020-10-05

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  twice in a program and you get a linker error for two one-definition-rule violations.

在一个程序中两次#include会引发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


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



浏览 36
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报