I've always used a *.h
file for my class definitions, but after reading some boost library code, I realised they all use *.hpp
. I've always had an aversion to that file extension, I think mainly because I'm not used to it.
What are the advantages and disadvantages of using *.hpp
over *.h
?
Here are a couple of reasons for having different naming of C vs C++ headers:
Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically
Naming, I've been on projects where there were libraries written in C and then wrappers had been implemented in C++. Since the headers usually had similar names, i.e. Feature.h vs Feature.hpp, they were easy to tell apart.
Inclusion, maybe your project has more appropriate versions available written in C++ but you are using the C version (see above point). If headers are named after the language they are implemented in you can easily spot all the C-headers and check for C++ versions.
Remember, C is not C++ and it can be very dangerous to mix and match unless you know what you are doing. Naming your sources appropriately helps you tell the languages apart.
I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers.
This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the extension
.hpp : C++ Headers
(Or .hxx, or .hh, or whatever)
This header is for C++ only.
If you're in a C module, don't even try to include it. You won't like it, because no effort is done to make it C-friendly (too much would be lost, like function overloading, namespaces, etc. etc.).
.h : C/C++ compatible or pure C Headers
This header can be included by both a C source, and a C++ source, directly or indirectly.
It can included directly, being protected by the __cplusplus
macro:
Which mean that, from a C++ viewpoint, the C-compatible code will be defined as extern "C".
From a C viewpoint, all the C code will be plainly visible, but the C++ code will be hidden (because it won't compile in a C compiler).
For example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#ifdef __cplusplus
extern "C"
{
#endif
void myCFunction() ;
#ifdef __cplusplus
} // extern "C"
#endif
#endif // MY_HEADER_H
Or it could be included indirectly by the corresponding .hpp header enclosing it with the extern "C"
declaration.
For example:
#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP
extern "C"
{
#include "my_header.h"
}
#endif // MY_HEADER_HPP
and:
#ifndef MY_HEADER_H
#define MY_HEADER_H
void myCFunction() ;
#endif // MY_HEADER_H
I always considered the .hpp
header to be a sort of portmanteau of .h
and .cpp
files...a header which contains implementation details as well.
Typically when I've seen (and use) .hpp
as an extension, there is no corresponding .cpp
file. As others have said, this isn't a hard and fast rule, just how I tend to use .hpp
files.
It does not matter which extension you use. Either one is OK.
I use *.h
for C and *.hpp
for C++.
EDIT [Added suggestion from Dan Nissenbaum]:
By one convention, .hpp files are used when the prototypes are defined in the header itself. Such definitions in headers are useful in case of templates, since the compiler generates the code for each type only on template instantiation. Hence, if they are not defined in header files, their definitions will not be resolved at link time from other compilation units. If your project is a C++ only project that makes heavy use of templates, this convention will be useful.
Certain template libraries that adhere to this convention provide headers with .hpp extensions to indicate that they do not have corresponding .cpp files.
another convention is to use .h for C headers and .hpp for C++; a good example would be the boost library.
Quote from Boost FAQ, File extensions communicate the "type" of the file, both to humans and to computer programs. The '.h' extension is used for C header files, and therefore communicates the wrong thing about C++ header files. Using no extension communicates nothing and forces inspection of file contents to determine type. Using '.hpp' unambiguously identifies it as C++ header file, and works well in actual practice. (Rainer Deyke)
I'm answering this as an reminder, to give point to my comment(s) on "user1949346" answer to this same OP.
So as many already answered: either way is fine. Followed by emphasizes of their own impressions.
Introductory, as also in the previous named comments stated, my opinion is C++
header extensions are proposed to be .h
if there is actually no reason against it.
Since the ISO/IEC documents use this notation of header files and no string matching to .hpp
even occurs in their language documentations about C++
.
But I'm now aiming for an approvable reason WHY either way is ok, and especially why it's not subject of the language it self.
So here we go.
The C++
documentation (I'm actually taking reference from the version N3690) defines that a header has to conform to the following syntax:
2.9 Header names header-name: < h-char-sequence > " q-char-sequence " h-char-sequence: h-char h-char-sequence h-char h-char: any member of the source character set except new-line and > q-char-sequence: q-char q-char-sequence q-char q-char: any member of the source character set except new-line and "
So as we can extract from this part, the header file name may be anything that is valid in the source code, too. Except containing '\n'
characters and depending on if it is to be included by <>
it is not allowed to contain a >
. Or the other way if it is included by ""
-include it is not allowed to contain a "
.
In other words: if you had a environment supporting filenames like prettyStupidIdea.>
, an include like:
#include "prettyStupidIdea.>"
would be valid, but:
#include <prettyStupidIdea.>>
would be invalid. The other way around the same.
And even
#include <<.<>
would be a valid includable header file name.
Even this would conform to C++
, it would be a pretty pretty stupid idea, tho.
And that's why .hpp
is valid, too.
But it's not an outcome of the committees designing decisions for the language!
So discussing about to use .hpp
is same as doing it about .cc
, .mm
or what ever else I read in other posts on this topic.
I have to admit I have no clue where .hpp
came from1, but I would bet an inventor of some parsing tool, IDE or something else concerned with C++
came to this idea to optimize some internal processes or just to invent some (probably even for them necessarily) new naming conventions.
But it is not part of the language.
And whenever one decides to use it this way. May it be because he likes it most or because some applications of the workflow require it, it never2 is a requirement of the language. So whoever says "the pp is because it is used with C++", simply is wrong in regards of the languages definition.
C++ allows anything respecting the previous paragraph. And if there is anything the committee proposed to use, then it is using .h
since this is the extension sued in all examples of the ISO document.
Conclusion:
As long you don't see/feel any need of using .h
over .hpp
or vise versa, you shouldn't bother. Because both would be form a valid header name of same quality in respect to the standard. And therefore anything that REQUIRES you to use .h
or .hpp
is an additional restriction of the standard which could even be contradicting with other additional restrictions not conform with each other. But as OP doesn't mention any additional language restriction, this is the only correct and approvable answer to the question
"*.h or *.hpp for your class definitions" is:
Both are equally correct and applicable as long as no external restrictions are present.
1From what I know, apparently, it is the boost framework that came up with that .hpp
extension.
2Of course I can't say what some future versions will bring with it!
I've recently started using *.hpp
for c++ headers.
The reason is that I use emacs as my primary editor and it enters automatically into c-mode when you load a *.h
file and into c++-mode when you load a *.hpp
file.
Apart that fact I see no good reasons for choosing *.h
over *.hpp
or vice-versa.
You can call your includes whatever you like.
Just need to specify that full name in the #include
.
I suggest that if you work with C to use .h
and when with C++ to use .hpp
.
It is in the end just a convention.
I prefer .hpp for C++ to make it clear to both editors and to other programmers that it is a C++ header rather than a C header file.
Codegear C++Builder uses .hpp for header files automagically generated from Delphi source files, and .h files for your "own" header files.
So, when I'm writing a C++ header file I always use .h.
C++ ("C Plus Plus") makes sense as .cpp
Having header files with a .hpp extension doesn't have the same logical flow.
Bjarne Stroustrup and Herb Sutter have a statement to this question in their C++ Core guidelines found on: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-source which is also refering to the latest changes in the standard extension (C++11, C++14, etc.)
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.
I'm not a big fan of this convention because if you are using a popular library like boost, your consistency is already broken and you should better use .hpp.
Fortunately, it is simple.
You should use the .hpp extension if you're working with C++ and you should use .h for C or mixing C and C++.
In one of my jobs in the early 90's, we used .cc and .hh for source and header files respectively. I still prefer it over all the alternatives, probably because it's easiest to type.
As many here have already mentioned, I also prefer using .hpp for header-only libraries that use template classes/functions. I prefer to use .h for header files accompanied by .cpp source files or shared or static libraries.
Most of the libraries I develop are template based and thus need to be header only, but when writing applications I tend to separate declaration from implementation and end up with .h and .cpp files
It is easy for tools and humans to differentiate something. That's it.
In conventional use (by boost, etc), .hpp
is specifically C++ headers. On the other hand, .h
is for non-C++-only headers (mainly C). To precisely detect the language of the content is generally hard since there are many non-trivial cases, so this difference often makes a ready-to-use tool easy to write. For humans, once get the convention, it is also easy to remember and easy to use.
However, I'd point out the convention itself does not always work, as expected.
It is not forced by the specification of languages, neither C nor C++. There exist many projects which do not follow the convention. Once you need to merge (to mix) them, it can be troublesome.
.hpp itself is not the only choice. Why not .hh or .hxx? (Though anyway, you usually need at least one conventional rule about filenames and paths.)
I personally use both .h
and .hpp
in my C++ projects. I don't follow the convention above because:
The languages used by each part of the projects are explicitly documented. No chance to mix C and C++ in same module (directory). Every 3rdparty library is required to conforming to this rule.
The conformed language specifications and allowed language dialects used by the projects are also documented. (In fact, I even document the source of the standard features and bug fix (on the language standard) being used.) This is somewhat more important than distinguishing the used languages since it is too error-prone and the cost of test (e.g. compiler compatibility) may be significant (complicated and time-consuming), especially in a project which is already in almost pure C++. Filenames are too weak to handle this.
Even for the same C++ dialect, there may be more important properties suitable to the difference. For example, see the convention below.
Filenames are essentially pieces of fragile metadata. The violation of convention is not so easy to detect. To be stable dealing the content, a tool should eventually not only depend on names. The difference between extensions is only a hint. Tools using it should also not be expected behave same all the time, e.g. language-detecting of .h files on github.com. (There may be something in comments like shebang for these source files to be better metadata, but it is even not conventional like filenames, so also not reliable in general.)
I usually use .hpp
on C++ headers and the headers should be used (maintained) in a header-only manner, e.g. as template libraries. For other headers in .h
, either there is a corresponding .cpp
file as implementation, or it is a non-C++ header. The latter is trivial to differentiate through the contents of the header by humans (or by tools with explicit embedded metadata, if needed).
I use .h because that's what Microsoft uses, and what their code generator creates. No need to go against the grain.
In "The C++ Programming Language, Third Edition by Bjarne Stroustrup", the nº1 must-read C++ book, he uses *.h. So I assume the best practice is to use *.h.
However, *.hpp is fine as well!
.hpp
by the language itself at all.
There is no advantage to any particular extension, other than that one may have a different meaning to you, the compiler, and/or your tools. header.h
is a valid header. header.hpp
is a valid header. header.hh
is a valid header. header.hx
is a valid header. h.header
is a valid header. this.is.not.a.valid.header
is a valid header in denial. ihjkflajfajfklaf
is a valid header. As long as the name can be parsed properly by the compiler, and the file system supports it, it's a valid header, and the only advantage to its extension is what one reads into it.
That being said, being able to accurately make assumptions based on the extension is very useful, so it would be wise to use an easily-understandable set of rules for your header files. Personally, I prefer to do something like this:
If there are already any established guidelines, follow them to prevent confusion. If all source files in the project are for the same language, use .h. There's no ambiguity. If some headers are compatible with multiple languages, while others are only compatible with a single language, extensions are based on the most restrictive language that a header is compatible with. A header compatible with C, or with both C & C++, gets .h, while a header compatible with C++ but not C gets .hpp or .hh or something of the sort.
This, of course, is but one of many ways to handle extensions, and you can't necessarily trust your first impression even if things seem straightforward. For example, I've seen mention of using .h
for normal headers, and .tpp
for headers that only contain definitions for templated class member functions, with .h
files that define templated classes including the .tpp
files that define their member functions (instead of the .h
header directly containing both the function declaration and the definition). For another example, a good many people always reflect the header's language in its extension, even when there's no chance of ambiguity; to them, .h
is always a C header and .hpp
(or .hh
, or .hxx
, etc.) is always a C++ header. And yet again, some people use .h
for "header associated with a source file" and .hpp
for "header with all functions defined inline".
Considering this, the main advantage would come in consistently naming your headers in the same style, and making that style readily apparent to anyone examining your code. This way, anyone familiar with your usual coding style will be able to determine what you mean with any given extension with just a cursory glance.
The extension of the source file may have meaning to your build system, for example, you might have a rule in your makefile for .cpp
or .c
files, or your compiler (e.g. Microsoft cl.exe
) might compile the file as C or C++ depending on the extension.
Because you have to provide the whole filename to the #include
directive, the header file extension is irrelevant. You can include a .c
file in another source file if you like, because it's just a textual include. Your compiler might have an option to dump the preprocessed output which will make this clear (Microsoft: /P
to preprocess to file, /E
to preprocess to stdout
, /EP
to omit #line
directives, /C
to retain comments)
You might choose to use .hpp
for files that are only relevant to the C++ environment, i.e. they use features that won't compile in C.
Success story sharing