Best practice: Use of stdint types in a header file
Question
What's the best way to ensure that stdint.h
is included for headers that use the types from that header?
The alternatives I can see are:
- including
stdint.h
in the header itself (dangerous, is it not?) - flagging something to the compiler if it's not included when parsing the header (something like
#ifndef _STDINT_H
with an accompanying#error "stdint.h not included"
- Educating the other developer in always including
stdint.h
before any of my headers that require it, either using comments, conversation, documentation or a mixture of all three (the last one being preferable).
If there are any other alternatives worth mentioning, feel free to do so - I'm just guessing at what I should do here.
Solution
If you use types from stdint.h
in your header, you really should include stdint.h
in that header.
It is generally preferred to include the least amount of files from a header to reduce compile time. Therefore, whenever possible, you should forward declare types in headers. Since the types from stdint.h
cannot be forward declared (they're just typedefs of primitive types), there is no other option than including stdint.h
in the header.
OTHER TIPS
I my oppinion, including header files in header files is ok if you use include guards.
Something like
# ifndef HEADER
# define HEADER
# include header.h
# endif