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:
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
(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.).
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:
extern "C"
.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