'How to process C++ file to remove ifdef'd out code

I have inherited a piece of C++ code which has many #ifdef branches to adjust the behaviour depending on the platform (#ifdef __WIN32, #ifdef __APPLE__, etc.). The code is unreadable in its current form because these preprocessor directives are nested, occur in the middle of functions and even in the middle of multi-line statements.

I'm looking for a way of somehow specifying some preprocessor tags and getting out a copy of the code as if the code had been pre-processed with those flags. I'd like the #include directives to be left untouched, though. Example:

#include <iostream>

#ifdef __APPLE__
std::cout << "This is Apple!" << std::endl;
#elif __WIN32
std::cout << "This is Windows" << std::endl;
#endif

would turn into:

#include <iostream>

std::cout << "This is Apple!" << std::endl;

after being processed by: tool_i_want example.cpp __APPLE__.

I've hacked a quick script that does something similar, but I'd like to know of better tested and more thorough tools. I am running a Linux distribution.

I have decided against just running the C-preprocessor because if I'm not mistaken it will expand the header files, which would make everything more unreadable.



Solution 1:[1]

Use unifdef. It is designed for that purpose.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Basile Starynkevitch