Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom headers higher than standard?

Tags:

c++

header

Is it reasonable to put custom headers higher in include section than standard headers? For example include section in someclass.hpp:

#include "someclass.h"
#include "global.h"

#include <iostream>
#include <string>

Is it best practice? What is the profit if it is?

like image 872
fat Avatar asked Dec 02 '22 23:12

fat


1 Answers

The reason is that if you forget to include a dependent header in someclass.h, then whatever implementation file includes it as the first header, will get a warning/error of undefined or undeclared type, and whatnot. If you include other headers first, then you could be masking that fact - supposing the included headers define the required types, functions, etc. Example:

my_type.h:

// Supressed include guards, etc
typedef float my_type;

someclass.h:

// Supressed include guards, etc
class SomeClass {
public:
    my_type value;
};

someclass.cpp:

#include "my_type.h" // Contains definition for my_type.
#include "someclass.h" // Will compile because my_type is defined.
...

This will compile fine. But imagine you want to use use SomeClass in your program. If you don't include my_type.h before including someclass.h, you'll get a compiler error saying my_type is undefined. Example:

#include "someclass.h"
int main() {
    SomeClass obj;
    obj.value = 1.0;
}
like image 158
jweyrich Avatar answered Dec 23 '22 04:12

jweyrich