Previous: C++ basics Up: C++ basics Next: Classes

This is an automatically generated documentation by LaTeX2HTML utility. In case of any issue, please, contact us at info@cfdsupport.com.


The C preprocessor (often abbreviated as cpp) is macro processor for C and C++ languages. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control. It’s purpose is, among others, to keep us from writing repetitive code. It is best thought of as a distinct program, which goes through the source code before the compilation itself and takes care of macro expansion, including files etc.

The macro has a name, a body and possibly a list of parameters. When macro name is used in the code, preprocessor replaces it with its body, possibly filling in parameters. Macro can occur in multiple places in the code, each time with different values of parameters. This, when used wisely, can greatly reduce multiplicity of the code and improve the code readability.

Following piece of code shows example of using two most used preprocessor directives, #include and #define. The code can be found on your USB sticks in training/cpp_tutorial in directory preprocessor in file main.cpp.


#define HW "Hello world!\n"
#define HELLO(str) "Hello "#str"!\n"

int main()
   std::cout << HW;
   std::cout << HELLO(everyone);
   return 0;

Let’s have a look how the code looks like after expanding the macros. To do so, go to the directory with the code and run command

# g++ -E main.cpp

The -E switch tells the compiler to run only the preprocessor. You should get very long output with last lines looking as follows:

int main()
   std::cout << "Hello world!\n";
   std::cout << "Hello ""everyone""!\n";
   return 0;

Many lines of code in the beginning come from inclusion of iostream. Macros in the main() function got expanded, the second one using “everyone” as parameter. Let’s check, that the code works as intended. Compile and run the code to see its output. 196 Use the following command to compile the code:

# g++ main.cpp -o helloWorld

197 In Windows, command is the same except for the compiler:

# x86_64w64-mingw32-g++ main.cpp -o helloWorld

And then run the the compiled program:

# ./helloWorld

And you should get the following output:

# Hello world!
# Hello everyone!

Previous: C++ basics Up: C++ basics Next: Classes