The Wayback Machine - https://web.archive.org/web/20240930181722/https://www.geeksforgeeks.org/cc-preprocessors/
Open In App

C Preprocessors

Last Updated : 28 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

preprocessors in c

You can see the intermediate steps in the above diagram. The source code written by programmers is first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an expanded source code file is generated named “program.i”. This expanded file is compiled by the compiler and an object code file is generated named “program.obj”. Finally, the linker links this object code file to the object code of the library functions to generate the executable file “program.exe”. 

Preprocessor Directives in C

Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get executed. We can place these preprocessor directives anywhere in our program.

Examples of some preprocessor directives are: #include, #define, #ifndef, etc.

Note Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include the code or content of the specified file in your program.

List of preprocessor directives in C

The following table lists all the preprocessor directives in C:

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

#elif

Combines else and if for another condition check

#endif

Used to mark the end of #if, #ifdef, and #ifndef

These preprocessors can be classified based on the type of function they perform.

Types of C Preprocessors

There are 4 Main Types of Preprocessor Directives:  

  1. Macros
  2. File Inclusion
  3. Conditional Compilation
  4. Other directives

Let us now learn about each of these directives in detail. 

1. Macros

In C, Macros are pieces of code in a program that is given some name. Whenever this name is encountered by the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro.

Syntax of Macro Definition

#define token value

where after preprocessing, the token will be expanded to its value in the program.

Example of Macro

C
// C Program to illustrate the macro
#include <stdio.h>

// macro definition
#define LIMIT 5

int main()
{
    for (int i = 0; i < LIMIT; i++) {
        printf("%d \n", i);
    }

    return 0;
}

Output
0 
1 
2 
3 
4 

In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.

Note There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-colon to end.

There are also some Predefined Macros in C which are useful in providing various functionalities to our program.

Macros With Arguments

We can also pass arguments to macros. Macros defined with arguments work similarly to functions.

Example

#define foo(a, b) a + b
#define func(r) r * r

Let us understand this with a program:

C
// C Program to illustrate function like macros
#include <stdio.h>

// macro with parameter
#define AREA(l, b) (l * b)

int main()
{
    int l1 = 10, l2 = 5, area;

    area = AREA(l1, l2);

    printf("Area of rectangle is: %d", area);

    return 0;
}

Output
Area of rectangle is: 50

We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it replaces it with the statement (l*b). Not only this, but the values passed to the macro template AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.

2. File Inclusion

This type of preprocessor directive tells the compiler to include a file in the source code program. The #include preprocessor directive is used to include the header files in the C program.

There are two types of files that can be included by the user in the program:

Standard Header Files

The standard header files contain definitions of pre-defined functions like printf(), scanf(), etc. These files must be included to work with these functions. Different functions are declared in different header files.
For example, standard I/O functions are in the ‘iostream’ file whereas functions that perform string operations are in the ‘string’ file. 

Syntax

#include <file_name>

where file_name is the name of the header file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard directory.

User-defined Header Files

When a program becomes very large, it is a good practice to divide it into smaller files and include them whenever needed. These types of files are user-defined header files.

Syntax

#include "filename"

The double quotes ( ” ” ) tell the compiler to search for the header file in the source file’s directory.

3. Conditional Compilation

Conditional Compilation in C directives is a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific part of the program based on some conditions. There are the following preprocessor directives that are used to insert conditional code:

  1. #if Directive
  2. #ifdef Directive
  3. #ifndef Directive
  4. #else Directive
  5. #elif Directive
  6. #endif Directive

#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the preprocessing of these directives is completed.

Syntax

#ifdef macro_name
// Code to be executed if macro_name is defined
#ifndef macro_name
// Code to be executed if macro_name is not defined
#if constant_expr
// Code to be executed if constant_expression is true
#elif another_constant_expr
// Code to be excuted if another_constant_expression is true
#else
// Code to be excuted if none of the above conditions are true
#endif

If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally, but if it is not defined, the compiler will simply skip this block of statements.

Example

The below example demonstrates the use of #include #if, #elif, #else, and #endif preprocessor directives.

C
//program to demonstrates the use of #if, #elif, #else,
// and #endif  preprocessor directives.
#include <stdio.h>

// defining PI
#define PI 3.14159

int main()
{
  
#ifdef PI
    printf("PI is defined\n");
  
#elif defined(SQUARE)
    printf("Square is defined\n");
#else
    #error "Neither PI nor SQUARE is defined"
#endif
  
#ifndef SQUARE
    printf("Square is not defined"); 
#else
    cout << "Square is defined" << endl;
#endif

    return 0;
}

Output
PI is defined
Square is not defined

4. Other Directives 

Apart from the above directives, there are two more directives that are not commonly used. These are:

  1. #undef Directive
  2. #pragma Directive

1. #undef Directive

The #undef directive is used to undefine an existing macro. This directive works as:

#undef LIMIT

Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT” statement will evaluate as false. 

Example

The below example demonstrates the working of #undef Directive.

C
#include <stdio.h>

// defining MIN_VALUE

#define MIN_VALUE 10

int main() {
    // Undefining and redefining MIN_VALUE
printf("Min value is: %d\n",MIN_VALUE);
  
//undefining max value   
#undef MIN_VALUE
  
// again redefining MIN_VALUE  
#define MIN_VALUE 20

    printf("Min value after undef and again redefining it: %d\n", MIN_VALUE);

    return 0;
}

Output
Min value is: 10
Min value after undef and again redefining it: 20

2. #pragma Directive

This directive is a special purpose directive and is used to turn on or off some features. These types of directives are compiler-specific, i.e., they vary from compiler to compiler.

Syntax

#pragma directive

Some of the #pragma directives are discussed below: 

  1. #pragma startup: These directives help us to specify the functions that are needed to run before program startup (before the control passes to main()).
  2. #pragma exit: These directives help us to specify the functions that are needed to run just before the program exit (just before the control returns from main()).

Below program will not work with GCC compilers.

Example

The below program illustrate the use of #pragma exit and pragma startup

C
// C program to illustrate the #pragma exit and pragma
// startup
#include <stdio.h>

void func1();
void func2();

// specifying funct1 to execute at start
#pragma startup func1
// specifying funct2 to execute before end
#pragma exit func2

void func1() { printf("Inside func1()\n"); }

void func2() { printf("Inside func2()\n"); }

// driver code
int main()
{
    void func1();
    void func2();
    printf("Inside main()\n");

    return 0;
}


Expected Output

Inside func1()
Inside main()
Inside func2()

The above code will produce the output as given below when run on GCC compilers: 

Inside main()c

This happens because GCC does not support #pragma startup or exit. However, you can use the below code for the expected output on GCC compilers. 

C
#include <stdio.h>

void func1();
void func2();

void __attribute__((constructor)) func1();
void __attribute__((destructor)) func2();

void func1()
{
    printf("Inside func1()\n");
}

void func2()
{
    printf("Inside func2()\n");
}

int main()
{
    printf("Inside main()\n");

    return 0;
}

Output
Inside func1()
Inside main()
Inside func2()

In the above program, we have used some specific syntaxes so that one of the functions executes before the main function and the other executes after the main function.

#pragma warn Directive

This directive is used to hide the warning message which is displayed during compilation. We can hide the warnings as shown below: 

  • #pragma warn -rvl: This directive hides those warnings which are raised when a function that is supposed to return a value does not return a value.
  • #pragma warn -par: This directive hides those warnings which are raised when a function does not use the parameters passed to it.
  • #pragma warn -rch: This directive hides those warnings which are raised when a code is unreachable. For example, any code written after the return statement in a function is unreachable.

Frequently Asked Questions on C Preprocessors

How Does a Macro with Arguments Differ from a Function in C?

Macros with arguments are expanded at compile time, unlike functions, which are executed at runtime. This means that the macro performs text substitution before the program is compiled, so it doesn’t have the overhead of a function call that results in a faster execution but lack type checking.

What are the Main Differences Between Macros and Functions in C?

  • Macros expand at compile time; functions run at runtime.
  • Functions occupy memory in the code section; macros do not.
  • Functions are type-checked; macros are not.
  • Macros can be faster than functions due to the lack of function call overhead

Why Might One Choose to Use a Macro Instead of a Function in C?

Macros can be faster because they avoid function call overhead, making them suitable for simple, repetitive tasks.

Why Avoid Macros in Place of Functions?

Macros lack type checking, leading to potential bugs. Functions are safer and easier to debug.

Are Macros Stored in Memory like Functions?

No, macros are expanded during compilation and don’t exist in the final binary, unlike functions, which are stored in the code section of memory, that allows them to be called and executed at runtime.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.



Similar Reads

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 run-time or say during the compile-time. In a ver
6 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 25 C Projects with Source Codes for 2024
If you're looking for project ideas to boost your C Programming skills, you're in the right spot. Programming is about problem-solving and adapting to ever-changing technology. Start with C, the foundation of many modern languages, to refine your programming abilities. Despite being introduced 50 years ago, C remains a top choice for beginners due
14 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library <stdio.h> and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
Length of Array in C
The Length of an array in C refers to the number of elements in the array. It must be specified at the time of declaration. It is also known as the size of an array that is used to determine the memory required to store all of its elements. In C Programming language, we don't have any pre-defined function to find the length of the array but we can
4 min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Array of Strings in C
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array. Syntax: char variable_name[r][m] = {list of string};Here, var_name is the name of the var
2 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
Modulo Operator (%) in C/C++ with Examples
In C or C++, the modulo operator (also known as the modulus operator), denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division which is also called the modulus of the operation. Syntax of Modulus OperatorIf x and y are integers, then the expression: x % y;pronounced as "x mod y". For examp
5 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
INT_MAX and INT_MIN in C/C++ and Applications
Most of the time, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, C/C++ has certain macros to represent these numbers, so that these can be directly assigned to the variable without ac
7 min read
C strcmp()
In C language, the <string.h> header file contains the Standard String Library that contains some useful and commonly used string manipulation functions. In this article, we will see how to compare strings in C using the function strcmp(). What is strcmp() in C?C strcmp() is a built-in library function that is used for string comparison. This
6 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
Command Line Arguments in C
The most important function of C is the main() function. It is mostly defined with a return type of int and without parameters. int main() { ... } We can also give command-line arguments in C. Command-line arguments are the values given after the name of the program in the command-line shell of Operating Systems. Command-line arguments are handled
4 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Converting Number to String in C++
In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at some methods to convert an integer or a number to a s
4 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
fork() in C
The Fork system call is used for creating a new process in Linux, and Unix systems, which is called the child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call. The child process uses t
6 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
bool in C
The bool in C is a fundamental data type in most that can hold one of two values: true or false. It is used to represent logical values and is commonly used in programming to control the flow of execution in decision-making statements such as if-else statements, while loops, and for loops. In this article, we will explore how to use the bool data t
5 min read