C Preprocessor Directives
Last Updated :
19 Jul, 2024
In almost every C program we come across, we see a few lines at the top of the program preceded by a hash (#) sign. They are called preprocessor directives and are preprocessed by the preprocessor before actual compilation begins. The end of these lines is identified by the newline character ‘\n’, no semicolon ‘;’ is needed to terminate these lines. Preprocessor directives are mostly used in defining macros, evaluating conditional statements, source file inclusion, pragma directives, line control, error detection, etc.
List of Preprocessor Directives in C
The following table lists all the preprocessor directives available in the C programming language:
| Preprocessor Directives | Description
|
|---|
#define
| Used to define a macro. |
#undef
| Used to undefine a macro. |
#include
| Used to include a file in the source code program. |
#ifdef
| Used to include a section of code if a certain macro is defined by #define. |
#ifndef
| Used to include a section of code if a certain macro is not defined by #define. |
#if
| Check for the specified condition. |
#else
| Alternate code that executes when #if fails. |
#endif
| Used to mark the end of #if, #ifdef, and #ifndef. |
#error
| Used to generate a compilation error message.
|
#line
| Used to modify line number and filename information. |
#pragma once
| To make sure the header is included only once.
|
#pragma message
| Used for displaying a message during compilation.
|
Types of Preprocessor Directives in C
In C, preprocessor directives are categorized based on their functionalities following are the types of preprocessor directives:
- Macro Definition
- File Inclusion directive
- Conditional Compilation
- Line control
- Error directive
- Pragma direcive
Let us now have a look at each one of these directives in detail:
1. #define – Macro Directive
In C, macro definition directives uses the #define preprocessor directive to define the macros and symbolic constants. We use #define directive to define macro. Macro are basically the symbolic names that represents lines of code or some values. This directive is used to create constants or to define short, reusable codes.
Syntax
#define token value
Example
C
// C program to illustrate the use of #define directive
#include <stdio.h>
// Defining a macro for PI
#define PI 3.14159
int main()
{
// Using the PI macro to calculate
double radius = 8.0;
double area = PI * radius * radius;
// Displaying the calculated area
printf("Area of the circle is: %f\n", area);
return 0;
}
OutputArea of the circle is: 201.061760
2. #include – File Inclusion Directive
#include is one of the file inclusion directive in C. #include preprocessor directive is used to include the content of one file to another file i.e. source code during the preprocessing stage. This is done to easily organize the code and increase the reusability of code.
Syntax
#include <file_name>
or
#include "filename"
Here, file inclusion with double quotes ( â â ) tells the compiler to search for the header file in the directory of source file.
Example
The below example demonstrates the use of file inclusion directive #include.
C
// C program to demonstrate the use of file inclusion
// directive #include.
#include <stdio.h> // includng header file for Standard input/output functions
#include <stdlib.h> // includng header file for Standard library functions
int main()
{
// Using standard input/output functions from stdio.h
printf("Hello, Geek!\n");
// Using standard library functions
int num1 = 10, num2 = 5;
int sum = num1 + num2;
// displayng the result using printf from stdio.h
printf("Sum: %d\n", sum);
return 0;
}
OutputHello, Geek!
Sum: 15
3. #if, #ifdef, #else, #elif, #endif – Conditional Compilation
Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions. In our C Preprocessors article, we have discussed about such directives.
#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, â#endifâ always matches the nearest â#ifdefâ (or â#ifndefâ, or â#ifâ). Also, you can’t begin a conditional group in one file and finish it in another.
Syntax
#ifdef MACRO
controlled text
#endif
#ifndef: In #ifdef directive if the macroname is defined, then the block of statements after the #ifdef directive will be executed normally but in case it is not defined, the compiler will simply skip this block of statements. The #ifndef directive is simply the opposite of #ifdef directive. In case of #ifndef , the block of statements between #ifndef and #endif will get executed only if the macro or the identifier with #ifndef is not defined.
Syntax
ifndef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
endif
Note: If the macro with name as âmacronameâ is not defined using the #define directive then only the block of statements will execute.
#if, #else and #elif: All these directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive results in a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed.
Syntax
#if macro_condition
statements
#elif macro_condition
statements
#else
statements
#endif
Example
The below example demonstrates the use of conditional directives.
C
// C program to demonstrate the use of conditional
// directives.
#include <stdio.h>
#define gfg 7
#if gfg > 200
#undef gfg
#define gfg 200
#elif gfg < 50
#undef gfg
#define gfg 50
#else
#undef gfg
#define gfg 100
#endif
void printValue(int value) { printf("%d", value); }
int main()
{
printValue(gfg); // gfg = 50
return 0;
}
Note: the entire structure of #if, #elif and #else chained directives ends with #endif.
4. #line – Line Control
Whenever we compile a program, there are chances of occurrence of some error in the program. Whenever compiler identifies error in the program it provides us with the filename in which error is found along with the list of lines and with the exact line numbers where the error is. This makes easy for us to find and rectify error. However we can control what information should the compiler provide during errors in compilation using the #line directive.
Syntax
#line number "filename"
number – line number that will be assigned to the next code line. The line numbers of successive lines will be increased one by one from this point on. “filename” – optional parameter that allows to redefine the file name that will be shown.
Example
C
// C program to demonstrate the use of #line
#include <stdio.h>
// Macro to print the current line number
#define PrintLineNum \
printf("Line number is %d in file named %s\n", \
__LINE__, __FILE__)
int main()
{
// Print the original line number
PrintLineNum;
// Using #line to change line number and file name
// temporarily
#line 20 "main.c"
PrintLineNum;
// revert to the original line number and file name
#line 30 "index.c"
PrintLineNum;
return 0;
}
OutputLine number is 13 in file named ./Solution.c
Line number is 20 in file named main.c
Line number is 30 in file named index.c
5. #error – Error Directive
The #error directive aborts the compilation process when it is found in the program during compilation and produces an error which is optional and can be specified as a parameter.
Syntax
#error optional_error
Here, optional_error is any error specified by the user which will be shown when this directive is found in the program.
Example
The below example demonstrate the use of error directive to display custom error message.
C
// C program to demonstrate the use of error directive to
// display custom error message.
#include <stdio.h>
// #define GeeksforGeeks // not Defining the symbol
// GeeksforGeeks
#ifndef GeeksforGeeks
#error GeeksforGeeks not found!
#endif
int main()
{
printf("Hello, GeeksforGeeks!\n");
return 0;
}
Output
error: #error GeeksforGeeks not found !
6. #pragma – Pragma directive
The #pragma directive is used to provide the compiler some extra information and hence it is compiler dependent so we can say that it’s behavior vary according to the compiler we are using. The pragma directive basically gives the instructions to the compiler to turn on or turn off some feature and also to give some custom messages required.
Syntax
#pragma directive
Commonly used pragma directives are:
- #pragma message: used at compile time to print custom messages.
- #pragma once:
to guard the header files i.e the header file must be included only once. #pragma warning: to enable or disable the warnings.
Example
The below example demonstrates the use of pragma directive to display the custom message.
C
// C program to illustrate the use of Pragma to print the
// custom message
#include <stdio.h>
// not defining gfg to trigger pragma message
// #define GeeksforGeeks
int main()
{
#ifndef GeeksforGeeks
#pragma message(" GfG is not defined.")
#endif
printf("Hello geek!\n");
return 0;
}
Output
#pragma message: GfG is not defined.
Similar Reads
C Preprocessors
Preprocessors are programs that process the source code before compilation. Several steps are involved between writing a program and executing a program in C. Let us have a look at these steps before we actually start learning about Preprocessors. You can see the intermediate steps in the above diag
10 min read
C Preprocessor Directives
In almost every C program we come across, we see a few lines at the top of the program preceded by a hash (#) sign. They are called preprocessor directives and are preprocessed by the preprocessor before actual compilation begins. The end of these lines is identified by the newline character '\n', n
8 min read
How a Preprocessor works in C?
Compiling a C program - Behind the Scene A Preprocessor is a system software (a computer program that is designed to run on computer's hardware and application programs). It performs preprocessing of the High Level Language(HLL). Preprocessing is the first step of the language processing system. Lan
3 min read
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive "#include". C Header files offer the features like library functi
7 min read
Whatâs difference between header files "stdio.h" and "stdlib.h" ?
In C programming, standard header files provide various inbuilt functionalities and two of the most commonly used standard header files are stdio.h and stdlib.h. The <stdio.h> provides Standard Input Output tools such as printf(), scanf(), etc while <stdlib.h> provides some commonly used
4 min read
How to write your own header file in C?
As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question ar
4 min read
Macros and its types in C
In C, a macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;). E
6 min read
Interesting Facts about Macros and Preprocessors in C
In a C program, all lines that start with # are processed by preprocessor which is a special program invoked by the compiler. by this we mean to say that the â#â symbol is used to process the functionality prior than other statements in the program, that is, which means it processes some code before
6 min read
# and ## Operators in C
In C, # and ## operators are preprocessor operators using in macros for token manipulation. They are known as stringizing and token pasting operators and are used in macro definition with #define preprocessor. In this article, we will learn about these operators and how to use them in C programs. St
3 min read
How to print a variable name in C?
Printing a variable name means printing the identifier that is assigned to the variable. To print it, it should be in the form of string. This can be done by using stringification. Stringification in C is the method to convert the argument of a function like macro to a string. This can be done with
1 min read
Multiline macros in C
In this article, we will discuss how to write a multi-line macro. We can write multi-line macro same like function, but each statement ends with "\". Let us see with example. Below is simple macro, which accepts input number from user, and prints whether entered number is even or odd. #include <s
3 min read
Variable length arguments for Macros
Like functions, we can also pass variable length arguments to macros. For this we will use the following preprocessor identifiers.To support variable length arguments in macro, we must include ellipses (...) in macro definition. There is also "__VA_ARGS__" preprocessing identifier which takes care o
2 min read
Branch prediction macros in GCC
One of the most used optimization techniques in the Linux kernel is " __builtin_expect". When working with conditional code (if-else statements), we often know which branch is true and which is not. If compiler knows this information in advance, it can generate most optimized code. Let us see macro
2 min read
Difference between typedef and #define in C
In C, both typedef and #define can be used to create aliases for existing types or values, but their behaviors and implementation differ significantly. typedef is a keyword used to create type aliases(nicknames) that are checked by the compiler, while #define is a preprocessor directive that perform
3 min read
Difference between #define and const in C
In C, both #define and const define constant values, but these constants differ greatly in their behaviors and implementation. #define is a preprocessor directive used to define constants that are replaced by their value during preprocessing, before actual compilation begins. while const defines a t
3 min read