Avoiding #ifdefs

Bill Gatliff bgat at billgatliff.com
Wed Jan 6 09:13:37 EST 2010


Marek Vasut wrote:
>>
>> ifdefs here is what i want to avoid.
>>
>> +#ifdef CONFIG_MACH_OMAP_3630SDP
>> +	.phy.venc.type          = OMAP_DSS_VENC_TYPE_SVIDEO,
>> +#else
>> +	.phy.venc.type          = OMAP_DSS_VENC_TYPE_COMPOSITE,
>> +#endif
>>
>>     

I really don't think that this one is worth any effort to avoid, unless
at some point it's possible that the condition might be passed in from
the kernel command-line rather than just at compile-time.

Preprocessor macros serve a very useful purpose, and you should use them
wherever they're appropriate.  The above example is probably an
appropriate case, or at least is so mundane as to be harmless.

You used to see a lot of this in Linux kernel code:

    struct device_driver foo {
    ...
    #ifdef CONFIG_PM
       .suspend = foo_suspend,
       .resume = foo_resume,
    #endif
    ...
    };

    #ifdef CONFIG_PM
    int foo_suspend(...)
    {...}
    int foo_resume(...)
    {...}
    #endif


That one got to be annoying because it was so redundant, and it made the
#ifdef CONFIG_PM show up in multiple places.  A better approach has
turned out to be:

    #ifdef CONFIG_PM
    int foo_suspend(...)
    {...}
    #else
    #define foo_suspend NULL
    #endif

That lets you get rid of the #ifdef in the structure initializer,
without resorting to runtime structure setup.  (Note that setting up the
structure at runtime won't work if your kernel is execute-in-place).

If you have the same preprocessor macros showing up in many places,
particularly when they're woven into your executable code, then you need
to take a step back to see if there is a bigger-picture solution--- like
the CONFIG_PM example above.  But don't sweat their occasional use, at
all.  Just code it, and move on.  :)


b.g.

-- 
Bill Gatliff
Embedded systems training and consulting
http://billgatliff.com
bgat at billgatliff.com




More information about the linux-arm mailing list