我的类定义一直使用*.h文件,但在阅读了一些boost库代码后,我意识到它们都使用*.hpp。我一直很讨厌这个文件扩展名,我想主要是因为我不习惯它。

使用*.hpp而不是*.h的优点和缺点是什么?


当前回答

我最近开始在c++头文件中使用*.hpp。

原因是我使用emacs作为我的主编辑器,当你加载一个*.h文件时,它会自动进入c模式,当你加载一个*.hpp文件时,它会自动进入c++模式。

除此之外,我没有看到选择*.h而不是*.hpp或相反的理由。

其他回答

在我90年代早期的一份工作中,我们分别使用.cc和.hh作为源文件和头文件。在所有的选择中,我仍然更喜欢它,可能是因为它最容易打字。

Codegear c++ Builder使用.hpp作为从Delphi源文件自动生成的头文件,使用.h文件作为“自己的”头文件。

所以,当我写一个c++头文件时,我总是使用.h。

你可以随意命名你的include。

只需要在#include中指定全名。

我建议你使用C语言时使用.h,使用c++时使用.hpp。

它最终只是一种惯例。

Bjarne Stroustrup和Herb Sutter在他们的c++核心指南(https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-source)中对这个问题有一个声明,该指南也提到了标准扩展(c++ 11, c++ 14等)的最新变化。

SF.1: Use a .cpp suffix for code files and .h for interface files if your Y project doesn't already follow another convention 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). 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 may be different. Your IDE (if you use one) may have strong opinions about suffices.

我不是这种惯例的大粉丝,因为如果你正在使用像boost这样的流行库,你的一致性已经被打破了,你最好使用.hpp。

我最近开始在c++头文件中使用*.hpp。

原因是我使用emacs作为我的主编辑器,当你加载一个*.h文件时,它会自动进入c模式,当你加载一个*.hpp文件时,它会自动进入c++模式。

除此之外,我没有看到选择*.h而不是*.hpp或相反的理由。