Header file name

When I create a header file that will be used by several developers, it is considered good programming practice to make this header file self-sufficient in terms of all the definitions and declarations used in it.

For example:

Header File 1: types.h

#ifndef TYPES_H #define TYPES_H typedef unsigned int uint16 #endif 

Header File 2: myheader.h

 #ifndef MYHEADER_H #define MYHEADER_H uint16 myfunc(void); #endif 

I used uint16 in myheader.h without including types.h. Therefore, if someone wants to include myheader.h in the source file, he must first include "types.h" and then include "myheader.h". Thus, this actually forces the developer to include the header files in a specific order. I always thought of this as bad practice, but today I met some code in my company where, in order to get the function declared in one file, you need to include at least 4 other header files. So now I'm confused, I'm missing something, is there a place where this will be considered the expected behavior.

+7
source share
6 answers

Contaminating the global namespace with unnecessary types is bad practice. The best you can do is provide forward declarations where possible, and include other files if necessary. In a simplified case, you should include a header that defines uint16 in each header that uses it.

If, for example, you can forward-declare a type, that would be preferable. The rationale is that forward declarations are sufficient if you are not actually using this type. And if you use a type, you should include a header where it is explicitly specified.

+5
source

Itโ€™s better to just create some of them and then #include "types.h" in myheader.h. Do not make others think (at least not so).

+4
source

To be specific in answering your question: YES, the header file must be self-sufficient. It should include every header file needed to compile it.

In general, most modern libraries have security mechanisms, so the compiler only "sees" the header file once. First come first served. So donโ€™t get too hung up on it (although it never stops checking).

+3
source

An open header should contain all the definitions needed to use the interfaces that it provides, and nothing more.

+1
source

This is probably a matter of convention, but in almost all such cases myheader.h #includes types.h at the very beginning.

0
source

All headers should be self-sufficient, unless C # error is explicitly specified, unless certain definitions are defined.

I always put the appropriate header for the CPP file, as the first one includes to make sure they always compile.

0
source

All Articles