This question may seem rather basic, but coming from an engineering (non computer-science) background, I was unsure about what the snippets of '#
's were in some C++ code.
A quick search led me to the concise, well-explained cplusplus tutorial page on preprocessor directives.
But why bother with the concept of preprocessor directives at all? Is it not possible to write equivalent code that can assign values to constants, define subroutines/function/macros and handle errors?
I guess I ultimately want to know when it is good practice to use such preprocessor directives, and when it is not.
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
The #define directive is used to define values or macros that are used by the preprocessor to manipulate the program source code before it is compiled. Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace.
The preprocessor will process directives that are inserted into the C source code. These directives allow additional actions to be taken on the C source code before it is compiled into object code.
Preprocessor directives, such as #define and #ifdef , are typically used to make source programs easy to change and easy to compile in different execution environments. Directives in the source file tell the preprocessor to take specific actions.
You use preprocessor directives when you need to do something outside of the scope of the actual application. For instance, you'll see preprocessing done to include or not include code based on the architecture the executable is being built for. For example:
#ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers #include <windows.h> #else #include <unistd.h> #endif
Preprocessor directives are also used to guard includes so that classes/functions etc. are not defined more than once.
#ifndef MY_CLASS_6C1147A1_BE88_46d8_A713_64973C9A2DB7_H_ #define MY_CLASS_6C1147A1_BE88_46d8_A713_64973C9A2DB7_H_ class MyClass { .... }; #endif
Another use is for embedding versioning inside of code and libraries.
In the Makefile you have something along the lines of:
-D MY_APP_VERSION=4.5.1
While in the code you have
cout << "My application name version: " << MY_APP_VERSION << endl;
Answer 1: conditional code that has to vary depending on what sort of computer it works on.
Answer 2: enabling and disabling language extensions and compatibility features seen at compile time.
The preprocessor came from C, where there were many thing you could not express. Good C++ code finds less reasons to use it than C code did, but sadly it's not quite useless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With