Reputation: 113
In a C program, what are the valid places where I can include the header file #include <stdio.h>
?
I mean, generally, we include the header files at the beginning of the C program but if I include it inside the main()
function before any printf
or fprintf
function is used, will it give the same result as before or will it give any error?
Also, if such a declaration works fine, then what are the other places where I can declare this header file except at the beginning of the program?
Upvotes: 0
Views: 224
Reputation: 349
It is a good practice to include all the header files at the start of program.
Upvotes: 0
Reputation: 754690
The standard C headers must be included outside of any function or declaration — at file scope. Otherwise, they merely need to be included before their content is used.
C11 §7.1.2 Standard headers ¶4:
Standard headers may be included in any order; each may be included more than once in a given scope, with no effect different from being included only once, except that the effect of including
<assert.h>
depends on the definition ofNDEBUG
(see 7.2). If used, a header shall be included outside of any external declaration or definition, and it shall first be included before the first reference to any of the functions or objects it declares, or to any of the types or macros it defines. However, if an identifier is declared or defined in more than one header, the second and subsequent associated headers may be included after the initial reference to the identifier. The program shall not have any macros with names lexically identical to keywords currently defined prior to the inclusion of the header or when any macro defined in the header is expanded.
File scope means 'not inside a function or variable declaration, nor inside a struct or union declaration, or inside a typedef
, etc. For a formal definition, see C11 §6.2.1 Scopes of identifiers ¶4:
… If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit. …
Note that other headers from standards such as POSIX typically impose similar rules about where they can be included — they must be included at file scope.
However, other headers that are defined by users may be included wherever the programmer deems fit, subject to the included material leaving a syntactically valid translation unit (TU).
For example, there are "X-Macros" which often involve including a header multiple times in a single TU with different effects each time, and the #include
line can appear in the middle of a variable's initializer if that's the intended usage (and with X-Macros, it often is the intended usage).
static struct WhatEver data[] =
{
// #include <stdio.h> // Incorrect
#include "xmacro.h" // Possibly correct
};
Upvotes: 1