How to inspect your C++ code after preprocessor

In C++, the preprocessor is a tool that performs a series of transformations on the source code before it is compiled. It performs operations such as macro expansion, inclusion of header files, and conditional compilation.

One reason why it can be useful to see what the preprocessor produces in C++ is to understand how the code is transformed before it is compiled. The preprocessor can expand macros, substitute values, and perform other transformations that can significantly change the code structure. By examining the preprocessed output, developers can see how their code is transformed and check whether it is behaving as expected.

Additionally, examining the preprocessor output can help to diagnose errors and bugs in the code. By looking at the expanded code, developers can identify issues such as incorrect macro expansion, missing header files, or other problems that may arise during compilation.

Another reason why it can be useful to see the preprocessor output is to optimize the code. By examining the preprocessed code, developers can identify redundant operations, unnecessary inclusions of header files, and other areas where the code can be streamlined for better performance.

Overall, examining the preprocessor output in C++ can be a useful tool for understanding how the code is transformed before it is compiled, diagnosing errors and bugs, and optimizing the code for better performance.

How?

So, we understand that sometimes it can be very useful to see what the preprocessor actually produces before handling over the file to the compiler. You can inspect details and track down some type of problems. There are a few ways to do this:

gcc -E my_class.cpp -o my_class.ii

or

cpp my_class.cpp >> my_class.ii

Or if you work with qmake, you can use:

QMAKE_CXXFLAGS += -save-temps

In which case you will also get these *.ii files for each *.cpp file in your build folder. When we look inside such a file we see a lot more stuff than we wrote. For example line markers around the include statements:

# 1 "/usr/local/include/something.h" 1 3 4

The 3 means the import comes from a system header, 4 means the import should be wrapped in a ‘extern “C”‘ block.

This and what the other numbers mean is explained here: https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html

Happy Debugging!

Leave a Reply