×
>
<

Aptitude

Pre-processors in C++

Pre-processors in C++

Pre-processors in C++ are directives that provide instructions to the compiler to preprocess the information before actual compilation starts. These directives begin with the # symbol and are crucial for efficient coding. They are used for:

  • Including libraries
  • Macro substitutions
  • Conditional compilation
  • Other utilities such as file inclusion and line control

Types of Pre-processors
1. Macro Definitions
  
#define PI 3.14
#define AREA(r) (PI * (r) * (r))
  
Example Output
  
Area of circle with radius 5: 78.5
  
2. File Inclusion
  
#include <iostream>
#include "myheader.h"
  
Example Output
  
Contents of myheader.h included successfully.
  
3. Conditional Compilation
  
#ifdef DEBUG
    std::cout << "Debug mode" << std::endl;
#endif
  
Example Output
  
Debug mode
  
4. Other Directives
  
#undef PI
#pragma once
  
Example Output
  
PI undefined and single inclusion ensured.
  
Syntax for Pre-processor Directives –
  
// Macro Definition
#define PI 3.14

// File Inclusion
#include <iostream>
#include "myheader.h"

// Conditional Compilation
#ifdef DEBUG
  #define LOG(x) std::cout << x << std::endl
#else
  #define LOG(x)
#endif
  

Commonly used pre-processor directives in C++ include:

Macro Definitions

  
#define PI 3.14159
#define AREA(r) (PI * (r) * (r))
  

File Inclusion

  
#include <iostream>
#include "myheader.h"
  
Example
  
// Define a macro to find the square of a number
#define SQUARE(x) ((x) * (x))

// Include necessary libraries
#include <iostream>

// Conditional compilation to enable debugging
#ifdef DEBUG
  #define DEBUG_MSG(str) std::cout << "DEBUG: " << str << std::endl;
#else
  #define DEBUG_MSG(str)
#endif

int main() {
    int num = 5;
    std::cout << "Square of " << num << " is " << SQUARE(num) << std::endl;

    // Debug message
    DEBUG_MSG("This is a debug message");

    return 0;
}
  
Types of Pre-processor Directives in C++

  1. Macro Definitions
  2. File Inclusion
  3. Conditional Compilation
  4. Other Directives