Lesson 1.4. Preprocessor directives

Introduction

Preprocessor directives are also called compiler directives. It is a preliminary phase to the compilation. The compiler performs a number of operations on the code before transforming it into into machine language.

Among these preliminary operations, some are specified by the developer in the source code. These compilation directives always start with the character # and end with a line break.

You should not put a semicolon at the end of preprocessor directives. They are not instructions.

#include

#include allows you to insert another file into the code. When you use this directive, it is as if you were copying and pasting the file into the source code.

In 99% of the cases, #include is used to specify a library:

#include <stdio.h>

#define et #undef

#define allows you to declare a constant or an identifier. The latter can be deleted with #undef. Generally, this directive is used to declare constants:

#define PI 3.14159265359

Note the absence of a semicolon at the end of the line.

By convention, the names of constants are capitalized.

#ifdef, #else et #endif

You can specify to the preprocessor that a part of the code will not be compiled under certain conditions. This type of syntax is generally found in programs intended for several targets (Windows, Linux). The following example illustrates this: The || syntax represents an or. If _WIN32 is defined or _WIN64 is defined.

// stdio.h SDanDard Input Output (for printf)
#include <stdio.h>

int main(void) {

/* We use the directive to compile in a different way
on Linux and on Windows */
#if defined (_WIN32) || defined( _WIN64)
  printf ("Code for Windows\n");
#else
  printf ("Code for Linux\n");
#endif

  return 0;
}

Quiz

Preprocessor directives are also called...

Check Bravo! Try again...

When compiling, what is the preprocessor?

Check Bravo! The preprocessor prepares the code before it is compiled. Try again...

What is the syntax of a preprocessor directive?

Check Bravo! Compilation directives start with # and end with a line break. Try again...

Which directive is used to create a constant?

Check Bravo ! #define is used to define constants or identifiers. Try again...

Which syntax is correct?

Check Bravo! You should not put an equal sign or a semicolon at the end of the compilation directives. Try again...

Which directive should be used to include an external library?

Check Bravo! #include allows you to insert an external file, usually a library. Try again...

See also


Last update : 09/15/2023