Declarations,Definitions, Preprocessor & Linker in C++

Preprocessors:

The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts.The preprocessor examines the code before actual compilation of code begins and resolves all these directives before any code is actually generated by regular statements.

These preprocessor directives extend only across a single line of code.It starts with (#). As soon as a newline character is found, the preprocessor directive is ends. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (\).

Here are a few examples of directives:

Macros

macro is a label defined in the source code that is replaced by its value by the preprocessor before compilation.

To define macros in C++ we can use #define.Here is syntax:

#define identifier replacement

When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++ proper, it simply replaces any occurrence of identifier by replacement.

Here is an example:

#include <iostream>
using namespace std;
#define PI 3.1416 //replaces PI with 3.1416
int main() {  
  float radius = 3; 
  float area;
  area = PI * radius * radius;
  cout << "Area is " << area;
  return 0;
}

Here is another example:

#include <iostream>
using namespace std;
#define PI 3.1416 
#define AREA(r) r * r * PI 
// macro inside a macro
int main() {  
  float radius = 3; 
  float result;
  result = Area(radius); // macro as a function
  cout << "Area is " << area;
  return 0;
}

In the above two examples we saw macros are defined as an object as well as a function .Now we will see #undef in C++.

The #undef directive removes the current definition of the identifier . Consequently, subsequent occurrences of the identifier are ignored by the preprocessor. To remove a macro definition using  #undef , specify only the macro identifier. and no parameter list.

#define TABLE_SIZE 100
int table1[TABLE_SIZE];
#undef TABLE_SIZE
#define TABLE_SIZE 200
int table2[TABLE_SIZE];

This would result:

int table1[100];
int table2[200];

Conditional inclusions