srinivas
srinivas

Reputation: 101

When does #include <stdio.h> gets executed?

I started learning C programming. I went through this example

#include <stdio.h>
main() {
    printf("Hello, World");
}

It is said that main is start for the program. So, if main starts first, When and how does the first line gets executed?

Upvotes: 0

Views: 1509

Answers (4)

SergA
SergA

Reputation: 1174

Here illustrate generating of program/library (its the same for C):

Code build

The pre-processor simply processes text; it knows virtually nothing about C syntax. It scans the input program text, looking for the directives in which the first character on a line is a '#' or "escaped-newline" sequences. When it meets these directives, it takes certain actions, including other files to be processed (#include), defining symbols (#define), etc (#ifdef). It acts entirely on the program text and will happily pre-process text which may be complete gibberish for the C compiler.

A #include directive reads another file into the program at the point at which it is placed. It effectively merges two input files into a single output file for the compiler. So at this point pre-processor should find all included files (usually headers).

Links:

Upvotes: 2

Magisch
Magisch

Reputation: 7352

It doesn't, its an #include statement for the preprocessor, leading to it copy pasting the contents of the header file stdio.h to your program, allowing you to use its typedefs and structs and functions or macros. If you use functions, structs, typedefs or macros that are defined in a library, you need to #include that library, so your compiler knows where to get the definitions of the functions you used.

So generally speaking #include does not get executed when you run the program. Its relevant only when you compile your program.

Upvotes: 0

Fsmv
Fsmv

Reputation: 1176

As others have said it doesn't get executed by your program at all. What happens is before the code is passed to the compiler the exact contents of the file stdio.h, which exists on your computer somewhere the compiler can find it. This allows you to use the code in the file. When you include your own header files later it's important to remember that this is a basic copy paste operation and nothing weird happens.

These instructions that start with a # symbol are called preprocessor directives because they happen early on, before the compiler sees the code.

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180316

Preprocessor directives such as #include are evaluated and acted upon when your code is compiled, not when it runs. To the extent that they get "executed" at all, that happens outside the scope of any run of the program.

Generally speaking, including a header files such as stdio.h anyway only makes macros, function declarations, type declarations, and sometimes global variable declarations available to your program. There's no direct runtime effect.

Upvotes: 5

Related Questions