When I am creating a header file, that is going to be used by multiple developers, is it considered good programming practice to make that 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 have used uint16 in myheader.h without including types.h . So if anyone wants to include myheader.h in their source file they should first include “types.h” and then include “myheader.h”. So this is actually forcing the developer to include header files in a specific order. I had always thought of this as bad practice, but I came across some code today at my company where to get a function declared in one file you need to include at least 4 other header files. So now I am confused, am I missing something, is there any place where this would be considered expected behaviour.
Polluting the global namespace with unnecessary types is bad practice. The best you can do is provide forward-declarations where possible, and
includeother files where necessary. In your simplified case, you should include the header that definesuint16in every header that uses it.If, for example, you can forward-declare the type, this is to be prefered. The rationale is that a forward-declaration is enough if you don’t actually use the type. And if you do use the type, you should include the header where it’s declared explicitly.