C++ Preprocessor And Preprocessor Directives
Last Updated :
03 Jan, 2024
The preprocessor in C++ is used for processing the code before it is compiled by the compiler. It does many tasks such as including files, conditional compilation, using macros, etc. The preprocessor also allows the developers to select which portions of code should be included or excluded.
The code processed by the preprocessor is called expanded code and is generally saved with a ".i" file extension.
Preprocessor Directives in C++
In C++, the preprocessor directives are special commands that are used to instruct the preprocessor. It begins with a '#' symbol and tells the preprocessor to the modify source code before compilation. There are different preprocessor directives in C++ for different operations.
The below table lists frequently used preprocessor directives:
|
Links a header file in the source code.
|
Creates a symbolic or macro constant.
|
Deletes a macro that has already been defined.
|
Compilation that is conditional on the presence or absence of a macro.
|
Compilation that is conditional based on some expression.
|
Halts the compilation process and produces an error notice.
|
During compilation, a warning notice is shown.
|
Provide the compiler specific instructions.
|
1. #include
The #include preprocessor directive is used to include the contents of one file into the current one, use the #include directive. Header files are often included using this.
Syntax
#include <header_file_name>
or
#include "header_file_name"
The first one includes the header files from the source directory, whereas the second one includes the file from directory the source file is currently in.
Example
The below program demonstrates the use of #include preprocessor directive.
C++
// C++ program to demonstrate use of #include preprocessor
// directive
#include <iostream>
using namespace std;
int main()
{
cout << "GeeksforGeeks" << endl;
return 0;
}
2. #define
The #define preprocessor directive is used to define macros. Macro names are symbolic and may be used to represent constant values or short bits of code. Using #define
preprocessor makes our code more readable and easily maintainable as we can replace numbers and code snippets with a meaningful name.
Syntax
#define macro_name value
Example
The below program demonstrates the use of #define preprocessor directive.
C++
// C++ program to demonstrate the use of #define
// preprocessor directive.
#include <iostream>
using namespace std;
#define PI 3.14159
#define findSquare(x) (x * x)
int main()
{
double radius = 5.0;
double area = PI * findSquare(radius);
cout << "Area of circle: " << area;
return 0;
}
OutputArea of circle: 78.5397
3. #undef Directive
The #undef
preprocessor directive is used to undefined a previously defined macro (defined using #define). It is mainly used in the case when we want to redefine an existing macro or eliminate a macro definition associated with it from the code.
Syntax
#undef macro_name
Example
The below program demonstrates the use of #undef preprocessor directive.
C++
// C++ program to demonstrate the use of #undef preprocessor
// directive.
#include <iostream>
using namespace std;
#define MAX_VALUE 100
int main()
{
cout << "Max value: " << MAX_VALUE << endl;
// using undef to change MAX_VALUE
#undef MAX_VALUE
#define MAX_VALUE 200
cout << "Max value: " << MAX_VALUE;
return 0;
}
OutputMax value: 100
Max value: 200
4. #ifdef and #ifndef
The #ifdef
and #ifndef
are preprocessor directives that are used for conditional compilation. #ifndef verifies that a macro is not defined, #ifdef verifies that a macro is defined.
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
#endif
Note #ifdef and #ifndef are often used with the #endif
directive to include or exclude portions of code based on whether a certain macro is defined or not.
Example
The below program demonstrates the use of #ifdef and #ifndef preprocessor directives.
C++
// C++ program to demonstrate the use of #ifdef and #ifndef
// preprocessor directives.
#include <iostream>
using namespace std;
#define DEBUG
#define PI 3.14
int main()
{
// to check if DEBUG is defined
#ifdef DEBUG
cout << "Debug mode is ON" << endl;
#else
cout << "Debug mode is OFF" << endl;
#endif
// to check if PI is defined
#ifndef PI
cout << "PI is not defined" << endl;
#else
cout << "PI is defined" << endl;
#endif
return 0;
}
OutputDebug mode is ON
PI is defined
5. #if, #elif, #else, and #endif Directives (Conditional Directives)
The #if
, #elif
, #else
, #endif
, and #error
are conditional preprocessor directives these are used for conditional compilation. These are used to include or exclude a code based on some conditions specified.
Syntax
#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
Example
The below program demonstrates the use of #if, #elif, #else, and #endif preprocessor directives.
C++
// C++ program to demonstrates the use of #if, #elif, #else,
// and #endif preprocessor directives.
#include <iostream>
using namespace std;
// defining PI
#define PI 3.14159
int main()
{
#if defined(PI)
cout << "PI is defined" << endl;
#elif defined(SQUARE)
cout << "PI is not defined" << endl;
#else
#error "Neither PI nor SQUARE is defined"
#endif
return 0;
}
6. #error
The #error
directive is a preprocessor directive that is used to print a custom error message for compilation error. If any condition is not met or any particular requirement is not satified we can stop the compilation process using #error.
Syntax
#error error_message
Here, error_message
is the custom error message that you want to print when the #error is encountered.
Example
C++
// C++ program to demonstrate the use #error preprocessor
// directives.
#include <iostream>
using namespace std;
// not defining PI here
// #define PI 3.14159
int main()
{
#if defined(PI)
cout << "PI is defined" << endl;
#else
#error "Neither PI nor SQUARE is defined"
#endif
return 0;
}
Output
#error "Neither PI nor SQUARE is defined"
7. #warning
The #warning
preprocessor directive is used to generate a warning message during compilation. We can write custom warning messages generally used for any informational or debugging purpose. The compiler prints the warning message in console, to given an alert about any required condition or decisions that are made during the preprocessing stage.
Syntax
#warning message
Here, The message is any custom message that you want to print as an alert.
Example
The below program demonstrates the use of #warning preprocessor directive.
C++
// C++ program to demonstrate the use of #warning
// preprocessor directive.
#include <iostream>
using namespace std;
// not defining it to trigger the warning
//#define PI 3.14
#ifndef PI
#warning "PI is not defined!"
#endif
int main()
{
cout << "Hey! geek" << endl;
return 0;
}
Output
#warning "PI is not defined!"
Hey! geek
Note The warning message is printed when the code is compiled to the compiler output or console. It is compiler dependent. Hence, how the warning is displayed depends on the compiler you are using.
8. #pragma
The #pragma
directive is a compiler-specific instructions. Special instructions to the compiler are provided using the #pragma directive. It may be used, for instance, to alter compiler parameters or silence warnings.behavior and supported pragmas can vary between different compilers, as they are compiler-specific.
Syntax
#pragma directive
Commonly Used #pragma Flags
#pragma once: u
sed to i
nclude guard for header files.#pragma message
: used to print custom messages at the time of compilation.#pragma warning
: used to control warning behavior (like enable or disable warnings).#pragma optimize
: used to control optimization settings (manage optimization level).#pragma comment
: used to include some additional information in the object file(or specify linker options).
Example
C++
// C++ program to demonstrate the use of pragma preprocessor
// directive.
#include <iostream>
using namespace std;
#pragma once
// Defining PI to trigger a pragma message during
// compilation
#define PI 3.14
// to set aggressive optimization level
#pragma optimize("O3")
int main()
{
#ifdef PI
#pragma message("YES! PI is defined.")
#endif
cout << "In main function!\n";
return 0;
}
Output
#pragma message: YES! PI is defined.
In main function!
Conclusion
In summary, C++ preprocessor directives is a helpful tool to insert the code before actual compilation it improve the modularity, maintainability, and customisation of the code. It uses directives with a #
symbol to give instructions to compiler. It allows the developers to modify and manage the code for various conditions and manage the compilation process.
Similar Reads
C++ Preprocessor And Preprocessor Directives
The preprocessor in C++ is used for processing the code before it is compiled by the compiler. It does many tasks such as including files, conditional compilation, using macros, etc. The preprocessor also allows the developers to select which portions of code should be included or excluded. The code
7 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
Preprocessors in Objective-C
Preprocessors help the software experts in tasks like Reusability and Conditional compilation. This article focuses on discussing Preprocessors in Objective-C. What is Objective-C?The Objective-C language is a general-purpose, dynamic, and high-level programming language designed to enable object-or
6 min read
Difference between CSS Variables and Preprocessor
In this article, You will learn the differences between the CSS variables (cascading variables) and CSS preprocessors. They both implement the extra capabilities into CSS in their own different ways. CSS variables and preprocessors are two different things. Both have advantages and disadvantages. Th
6 min read
Convert C/C++ program to Preprocessor code
We use g++ compiler to turn provided Cpp code into preprocessor code. To see the preprocessor code generated by the CPP compiler, we can use the “-E” option on the command line: Preprocessor include all the # directives in the code. and also expands MACRO function. Syntax: g++ -E filename.cpp // MAC
1 min read
C++ Inline Namespaces and Usage of the "using" Directive Inside Namespaces
Prerequisite: Namespaces in C++ In C++, namespaces can be nested, and the resolution of namespace variables is hierarchical. An inline namespace is a namespace that uses the optional keyword inline in its original-namespace definition. This allows the identifiers of the nested inline namespace to be
3 min read
What is HTML Preprocessor ?
In this article, we will learn about the HTML pre-processor & will explore the pre-processor used for HTML. As its name suggests, the HTML pre-processor is the first stage of the whole compiling process which includes removing the comments, expanding the macros, the inclusion of the headers, etc
4 min read
Difference Between C Structures and C++ Structures
Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and
6 min read
Pre-increment and Post-increment in C/C++
In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning
4 min read
Type Inference in C++ (auto and decltype)
Type Inference refers to automatic deduction of the data type of an expression in a programming language. Before C++ 11, each data type needed to be explicitly declared at compile-time, limiting the values of an expression at runtime but after the new version of C++, keywords such as auto and declty
6 min read
C++ Functions - Pass By Reference
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory lo
5 min read
Precedence of postfix ++ and prefix ++ in C/C++
In C/C++, precedence of Prefix ++ (or Prefix --) has same priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix --) is higher than both Prefix ++ and *. If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right ass
4 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
C++ Programming and STL Facts
C++ is widely used for competitive programming. It is preferred because of its reliability, efficient execution, short snippets, etc. It has become adaptive by most coders as it also provides the benefits of Standard Template Library(STL). C++ STL is the backbone of programming. The inbuilt function
5 min read
Pointers in Objective-C
In Objective-C, Pointers are the variables that hold the memory address of another variable. You must have declared the pointer variable before its use. The size of the pointer depends on the architecture of the system. The pointer variable can be defined as a char, int, float, double, or any other
5 min read
Difference between std::set::upper_bound and std::upper_bound in C++
Prerequisites: Random-access Iterators, Bidirectional Iterators Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and
4 min read
Dereference Pointer in C
We know that the pointer variable can store the memory address in C language and in this article, we will learn how to use that pointer to access the data stored in the memory location pointed by the pointer. What is a Pointer? First of all, we revise what is a pointer. A pointer is a variable that
4 min read
Build a C++ Program that Have Multiple Source Code Files
In C++ generally, we saw only a single file program but what if we have multiple source code files and we have to build a program by using all these files? Let's see how we can build a C++ program with multiple source files without including them as header files. Use two or more source code files in
3 min read
Perl | References to a Subroutine
Prerequisite: Perl references Declaring References to a Subroutine In Perl, a reference is, exactly as the name suggests, a reference or pointer to another object. References actually provide all sorts of abilities and facilities that would not otherwise be available and can be used to create sophis
6 min read