Tutorial by Examples

A header file may be included by other header files. A source file (compilation unit) that includes multiple headers may therefore, indirectly, include some headers more than once. If such a header file that is included more than once contains definitions, the compiler (after preprocessing) dete...
In a nutshell, conditional pre-processing logic is about making code-logic available or unavailable for compilation using macro definitions. Three prominent use-cases are: different app profiles (e.g. debug, release, testing, optimised) that can be candidates of the same app (e.g. with extra log...
Macros are categorized into two main groups: object-like macros and function-like macros. Macros are treated as a token substitution early in the compilation process. This means that large (or repeating) sections of code can be abstracted into a preprocessor macro. // This is an object-like macro ...
Compile errors can be generated using the preprocessor. This is useful for a number of reasons some of which include, notifying a user if they are on an unsupported platform or an unsupported compiler. e.g. Return Error if gcc version is 3.0.0 or earlier. #if __GNUC__ < 3 #error "This cod...
Predefined macros are those that the compiler defines (in contrast to those user defines in the source file). Those macros must not be re-defined or undefined by user. The following macros are predefined by the C++ standard: __LINE__ contains the line number of the line this macro is used on, an...
An idiomatic technique for generating repeating code structures at compile time. An X-macro consists of two parts: the list, and the execution of the list. Example: #define LIST \ X(dog) \ X(cat) \ X(racoon) // class Animal { // public: // void say(); // }; #define...
Most, but not all, C++ implementations support the #pragma once directive which ensures the file is only included once within a single compilation. It is not part of any ISO C++ standard. For example: // Foo.h #pragma once class Foo { }; While #pragma once avoids some problems associated w...
# operator or stringizing operator is used to convert a Macro parameter to a string literal. It can only be used with the Macros having arguments. // preprocessor will convert the parameter x to the string literal x #define PRINT(x) printf(#x "\n") PRINT(This line will be converted to...

Page 1 of 1