简体   繁体   中英

CPP - Automatically remove #ifdef's and #ifndef's

I am using Geany IDE and I'm trying to get rid of all the #ifdef's and #ifndef's in my code. There are more than 1000 occurrences, they are nested and it is impossible to do it manually.

Here is an example:

#define EXPLAIN

#ifndef EXPLAIN
...
#endif
...
#ifdef EXPLAIN
...
#else
...
#endif

Somewhere the condition is #ifdef and somewhere it is #ifndef . You got the idea... Is there an easy way to get rid of them with all the corresponding code?

I will download and install any other software if needed.

A good solution is to run gcc using the -E flag which only runs the preprocessor. The following command:

gcc -E -D EXPLAIN file.cpp -o file.i

Preprocesses file.cpp and outputs file.i which is file.cpp preprocessed with the EXPLAIN macro defined.

Some useful flags if you want to produce an output file that is generally more readable and closer to what an input file would be expected to look like:

  • -D NAME to define the macro NAME with definition 1.
  • -fdirectives-only to process directives but not macros.
  • -C to keep comments.
  • -P to inhibit line markers.

Even with these flags, #include s will be replaced with the files you are including preprocessed. You can fix this by simply getting rid of the #include s, preprocessing the input file, and then adding the #include s in the output file.

Source: Using the GNU Compiler Collection (GCC): Preprocessor Options .

You can use unifdef to achieve this.

The unifdef utility selectively processes conditional C preprocessor #if and #ifdef directives. It removes from a file both the directives and the additional text that they delimit, while otherwise leaving the file alone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM