Search code examples
cincludec-preprocessorpragmapreprocessor-directive

Can the pre-processor directives like #include be placed only at the top of the program code?


I have used the #pragma directive inside functions without error or warning(especially #pragma pack()).But the following code shows the warning incompatible implicit declaration of built-in function 'printf'|:

int main(void)
{
    printf("Trial");
}

#include<stdio.h>

Further, here's is an extract from a book I have.The author has bad reviews on SO,especially for his generous use of void main(),but still I feel no author can be that bad to claim the following without reason:

Each of these preprocessor directives begin with a # symbol. The directives can be placed anywhere in a program but are most often placed at the beginning of a program, before the first function definition.

So can you tell me whether it's mandatory to use some preprocessor directives like #include at the top of the program while others like #pragma can be used anywhere in the program?

Edit After OUAH's remark I tried the following, but it doesn't give warning,it gives a big pile of errors.LOL.

int main(void)
{
    #include<stdio.h>
    printf("Trial");
}

Solution

  • An #include directive can be placed anywhere in a source file, but in C an identifier can usually not be used before it has been declared. That's the reason why you put the #include directive at the begining of your source file.

    void foo(void)
    {
        printf("Hello world\n");
    }
    
    extern int printf(const char *, ...);  // Error, the declaration should be put 
                                           // before the actual call