C - SPLessons

Chapter 32

C Preprocessor

C Preprocessor

Any C-program undergoes a pre-compilation process i.e before the program is compiled, there will be a process to check the program.This process is done by the C Preprocessor.

Preprocessor commands are called as Directives. Directives start with # symbol. Basically, there are 4 Preprocessor directives in C-compiler.

File Inclusion Directive

The files declared in header files can be used in the main program if once declared.

The file which consists of macro definitions and C-function declarations is called as header file. These can be described more clearly in the lesson Header Files.

Macro Substitution Directive

The #define is a macro, used to denote the constant values and they can be of any data types.

Eg: #define letter ‘A’

Suppose if there is #define max(a,b) in the program, it appears as #define max(a>b ? a:b) after the pre-process commands are compiled.

#include<stdio.h>
#define length 10
void main()
{
	printf("value of length is: %d \n", length );
}

Output:

value of length is: 10

Conditional Directives

According to the condition, a set of commands can be involved or removed in the program.

Below is the example for if,else and endif.

#include<stdio.h>
#define splessons 10
int main()
{
	#if (splessons==100)
	printf("if is included in the source code\n");
	#else
	printf("else is included in the source code\n");
	#endif
	return 0;
}

Output:

else is included in the source code

Example for ifdef,else,endif

#include<stdio.h>
#define splessons 100
int main()
{
	#ifdef splessons
	printf("splessons is defined.It can be added in the C file\n");
	#else
	printf("splessons is not defined\n");
	#endif
	return 0;
}

Output:

splessons is defined.It can be added in the C file

undef is used to un-define the existing macro variable.

#include<stdio.h>
#define height 100
void main()
{
	printf("First defined value for height: %d\n",height);
	#undef length
	#define length 20
	printf("length after undef and redefine:%d",length);
}

Output:

First defined value for height: 100
length after undef and redefine:20

Other Directives

#pragma directive

It will allow a directive to be defined and the effects are defined by implementation. If pragma is ignored,if it is not supported.

#error directive

It halts the compilation and returns the specified error message.

#line directive

Current line number is allowed by this directive and the apparent name of the current sourcecode filename to be changed.

Summary

  • Pre-processor performs pre-compilation.
  • Commands used in preprocessor are called preprocessor directives.
  • Macros, conditional directives and file inclusion directives are pre-processor directives.