Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what function does the compiler perform when it first reaches the #include statement in a C program

Tags:

c

I have come across this question while preparing for the interview:

What function does the compiler perform when it first reaches the #include statement in a C program?

I Googled it and as far as I could understand (If I am not wrong here) is that it includes all the macros or definitions that are defined in the #include filename into the source code at that point in the program.

Is this correct answer? And is that all the compiler does for the #include statement?

like image 855
user905 Avatar asked Mar 13 '23 00:03

user905


1 Answers

The #include directive is not processed by the compiler, but by the preprocessor. It takes the contents of the included file and essentially pastes it verbatim into the source file.

For example, if you have the following files:

myfunc.h:

int myfunc1(int x);
int myfunc2(int x);

main.c

#include "myfunc.h"

int main()
{
    int x = myfunc(2);
    return 0;
}

After main.c is processed by the preprocessor, the output will be the following:

int myfunc1(int x);
int myfunc2(int x);

int main()
{
    int x = myfunc(2);
    return 0;
}

Once the preprocessor has finished its job, then the compiler will work on the resulting file to create an object file, and the linker will create an executable.

Typically, the preprocessor and compiler steps happen together (and the linker as well), however you can run them as separate steps if need be.

like image 56
dbush Avatar answered Apr 28 '23 07:04

dbush