What is a preprocessor directive?

a preprocessor directive is a command by the user to the compiler to include something
ex- #include
(#include) is a preprocessor directive
() is the library which the compiler is commanded to include.

A Preprocessor directive is special code that gets parsed by a preprocessor before compiling. It performs various functions.

#include for instance, grabs the body of a .h file and copies it into the top (where you should be declaring your include statements) of your code. This lets your compiler compile and link to code defined elsewhere in a library.

It can also perform simple if/else statements. For instance, in each .h file you include, it should start with.

code here

What this does is it checks for the declaration of a preprocessor variable named. HEADER_FILE_NAME, which should be the name of our header file in all caps and underscores for spaces. If it does not detect that variable then it declares it, and then includes the rest of the code up to the #endif

This is useful for complicated projects that might have many different includes, that could potentially call on the same file. This ensures it only gets included once.

Also, you can define macros, which are basically glorified search/replace statements that your preprocessor runs.

For instance:
#define AND &&
Will look through your code for the word AND in all caps, and replace it with &&, allowing you to maybe make your code a little bit more readable

You can combine them together.

For instance:

#ifdef DEBUG
#define MAX(a,b) (a < b) ? b : a
#define MAX(a,b)

This allows you to call a macro, MAX from anywhere in your code. But only if you define DEBUG does it actually print out the code of the macro. If it’s not defined then it prints nothing.

There’s also a similar function called #undef to clear a defined variable. And there’s also an #else and #elif directive that works much like you’d think.

Privacy & Terms