Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which comes first? header guards, namespace and includes [closed]

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
like image 726
aCuria Avatar asked Oct 03 '11 16:10

aCuria


People also ask

Which choice is an include guard for the header?

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.

Should you use namespace in header file?

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.

Should I use header guards or pragma once?

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.

What is difference between namespace and header file?

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.


2 Answers

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
like image 82
Martin York Avatar answered Nov 15 '22 17:11

Martin York


What you've written is perfect. I don't think you need to change the order.

like image 24
Nawaz Avatar answered Nov 15 '22 18:11

Nawaz