Consider the possible things that may be found in a header file.
- Preprocessor macros. These will be available from the
#include
until the end of the .c
file that includes the header. Preprocessor macros are not concerned about C block scope (braces), so even though the header is inside a function, the macros will still be available after the end of the block.
- Declarations of types, variables and functions. Their scope will be the block where the
#include
directive is located. That's usually fine. However, it works only once. Almost all include files contain header guards, so that if the file is included more than once (which often happens due to headers requiring other headers) its content is only processed once. So if you #include
the same header in multiple functions, the declarations will only be available the first time.
- Definitions of functions (or variables, but that's extremely rare in headers). Headers sometime contain small
static
functions which the compiler can inline. These will cause the compilation to fail if the #include
directive is inside the function, because (barring some compiler extensions) you can't define a function inside another function.
So it's not just a matter of style: #include
inside a function often plain doesn't work.
You can put an #include
directive anywhere at file scope (i.e. outside a function) with no major technical ill effects. The entities that it defines would only be available below the #include
line. That's mostly a matter of style, but it's unusual and pointless so it will confuse maintainers. It can also lead to confusing errors if you define a variable or function of the same name as something declared in a header, because then any mismatch will be reported in the header (or in a header included in a header included … included in that header), possibly using weird implementation-specific syntax, rather than in your code.
So yes, it's bad. Group all your #include
directives near the top of the file, with nothing other than comments and the occasional #pragma
or #define
if instructed by your implementation's documentation.