#include in C
In C programming, the #include directive is used to include external header files in a C source code file. The purpose of the header files is to provide declarations and definitions for functions, data types, macros, and other constructs that are needed by the C program. Whether you are new to C or have some experience, this guide will help you to understand basics of #include in C effectively with examples. Let’s get started.
When a C source code file contains an #include directive, the preprocessor (a program that processes C source code before compilation) reads the specified header file and inserts its contents into the C program. This allows the C program to use the declarations and definitions provided by the header file.
Syntax of #include directive
#include <header_file_name.h>
Here, header_file_name.h is the name of the header file that is being included. The angle brackets <> are used to indicate that the header file is a system header file that is provided by the C compiler or the operating system.
Alternatively, it is also possible to include header files that are located in the same directory as the C source code file or in a subdirectory using double quotes ” ” instead of angle brackets <>.
For example:
#include "my_header_file.h"
Here, my_header_file.h is the name of the header file located in the same directory as the C source code file.
C program that uses the #include directive:
#include <stdio.h> // include standard input/output header fileint main() {
printf("Hello, world!\\n"); // use printf function from stdio.h header file
return 0;
}
In this program, the #include directive is used to include the standard input/output header file stdio.h. This header file provides the declaration for the printf() function, which is used to print the “Hello, world!” message to the console.
By including the stdio.h header file, the program can use the printf() function without having to define it explicitly in the source code. The preprocessor will read the stdio.h header file and insert the function declaration into the program.