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

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


当前回答

正如这里许多人已经提到的,我也更喜欢使用.hpp来处理使用模板类/函数的纯头文件库。我更喜欢使用.h作为头文件,附带.cpp源文件或共享或静态库。

我开发的大多数库都是基于模板的,因此只需要头文件,但在编写应用程序时,我倾向于将声明与实现分开,最终使用.h和.cpp文件

其他回答

使用哪个扩展名并不重要。两种都可以。

我用*.h表示C,用*.hpp表示c++。

你可以随意命名你的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++ ("C Plus Plus")作为.cpp是有意义的

扩展名为.hpp的头文件没有相同的逻辑流。

我更喜欢用.hpp作为c++头文件,这样可以让编辑器和其他程序员清楚地知道它是c++头文件,而不是C头文件。