Pratt
Pratt

Reputation: 861

Header file etiquette

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.

Upvotes: 7

Views: 770

Answers (6)

Kent
Kent

Reputation: 1036

All headers should be self-sufficient, unless explicitly stated with #error unless some defines are defined.

I always put the matching header for a CPP-file as the first include to make sure they are always compilable.

Upvotes: 0

Richard Sitze
Richard Sitze

Reputation: 8463

TO be specific in answering your question: YES, a header file should be self-sufficient. It should include every header file that is needed to allow it to compile.

In general, most modern library's have guards in place so that the header file(s) are only "seen" by the compiler once. First come, first serve. So don't get too hung-up on that (though it never hurts to verify).

Upvotes: 3

Stephen Canon
Stephen Canon

Reputation: 106117

A public header should provide all of the definitions necessary to use the interfaces that it exposes, and nothing more.

Upvotes: 1

noamtm
noamtm

Reputation: 12953

It's probably a matter of convention, but in almost all similar cases myheader.h #includes types.h at its very beginning.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

Polluting the global namespace with unnecessary types is bad practice. The best you can do is provide forward-declarations where possible, and include other files where necessary. In your simplified case, you should include the header that defines uint16 in 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.

Upvotes: 5

user529758
user529758

Reputation:

You'd better just create some include guards and then #include "types.h" into myheader.h. Don't make others think (at least not this way).

Upvotes: 4

Related Questions