I have been making files like this for awhile: Does the order make sense? or should the namespace and the #includes be swapped and why.
#ifndef CLASSNAME_H // header guards
#define CLASSNAME_H
#include "a.h" // includes in alphabetical order
#include "b.h" // user specified includes first
#include "c.h"
#include <vector> // then library includes
namespace MyNamespace
{
class ClassName
{
};
}
#endif
In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard, or file guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive.
You should definitely NOT use using namespace in headers for precisely the reason you say, that it can unexpectedly change the meaning of code in any other files that include that header. There's no way to undo a using namespace which is another reason it's so dangerous.
In addition to reducing errors, #pragma once is typically optimized to reduce the use of the preprocessor and file openings, making it faster than include guards. Note that many compilers optimize for this already, so it is possible they are equally fast.
A header file is a file that is intended to be included by source files. They typically contain declarations of certain classes and functions. A namespace enables code to categorize identifiers. That is, classes, functions, etc.
Yes. That's looks good.
Though I order my headers differently (but alphabetically is fine).
The only thing I would change is the include guard. I make the include my namspace as well as the class name. As several times I have classes with the same name (but in a different namespace) being used by the same code.
#ifndef MY_COMPANY_MY_NAME_SPACE_MYCLASSNAME_H // header guards
#define MY_COMPANY_MY_NAME_SPACE_MYCLASSNAME_H
#include "a.h" // includes in order of most specific to most general.
// My includes first.
// Then C++ headers <vector>
// I group all the containers together.
// Then C specific headers <sys/bla.h>
// Then C generic headers <ctype.h>
namespace MyNamespace
{
Class ClassName
{
};
}
#endif
What you've written is perfect. I don't think you need to change the order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With