ilcredo ilcredo - 3 years ago 235
C Question

How to get rid of ifdef's in a large c project

I got my hands on a opensource project coded in C. It uses #ifdef's for cross-compiling. There are a lot of ifdef's all over the source code. I want just to modify it for one platform. I was thinking to run it through compiler's pre-processor (Visual C++) but it will write the preprocessed result to a single file, which I don't need. Anybody knows a way to pre-process a project leaving it's structure intact (all files intact)? No grep, please.


I found a potential solution (it's amazing what you can find on the internet these days). It's boost.wave - a C++ preprocessor library which can do some interesting stuff. I don't know how it will turn out, but I will give it a try. Still, it's not the final answer, so if you have a solution then I will be glad to hear it.

Answer Source

There are two tools I know of that you could use to do this semi-automatically.

One is sunifdef (son of unifdef). AFAIK, this is no longer being maintained, though (and neither is unifdef on which it is based).

The other is coan, which is being actively maintained, and is a development of sunifdef.

See also: Is there a C pre-processor which eliminates #ifdef blocks based on values defined/undefined?.

As it happens, I'm still using sunifdef on the main project at work where I'm eliminating archaic code (for example, machines not supported since about 1996) from the code base. The only gotcha I have with it is that if a line goes in with parentheses like this:

#if (defined(MACH_A) && defined(PROP_P)) || (defined(MACH_B) && defined(PROP_Q)) || \
    (defined(MACH_C) && defined(PROP_R))

and we have -UMACH_C (so machine C is no longer supported), the output line is:

#if defined(MACH_A) && defined(PROP_P) || defined(MACH_B) && defined(PROP_Q)

Technically, that's fine; it is correct. It is just preferable to keep the extra, technically redundant parentheses in the expression.

One caveat: although I can answer for these compiling on Unix-based systems, I've not personally checked them out on Windows.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download