tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: KNF and the C preprocessor

On Mon, Dec 10, 2012 at 09:36:35AM -0600, David Young wrote:
> What do people think about setting stricter guidelines for using the
> C preprocessor than the guidelines from the past?  Example guidelines:
> 4 Computed constants.  The result of a function call may not be used
>   in a case-statement, even if the function evaluates to a constant at
>   compile time.  You have to use a macro, instead.

The alternative to constants would be C enums.
However C enums are such 2nd class citizens that they have problems
of their own.

> The C preprocessor MUST NOT be used for
> 1 In-line code: 'static inline' subroutines are virtually always better
>   than macros.

That rather depends on your definition of better.
a) #define macros tend to get optimised better.
b) __LINE__ (etc) have the value of the use, not the definition.

> 2 Configuration management: use the compiler & linker to a greater
>   extent than the C preprocessor to configure your program for your
>   execution environment, your chosen compilation options, et cetera.

Avoiding #ifdef inside code tends to be benefitial.
But, IMHO, there isn't much wrong with using #defines in header files
to remove function calls.

Using the compiler gets to be a PITA because of the warning/errors
about unreachable code.
> 3 Virtually anything else. :-)

There are some very useful techniques that allow a single piece of
source to be expanded in multiple ways.
That is useful for things like defining text string (eg for errors)
on the same line as the constant.

I've also used it (not in the NetBSD source tree) to define
extern function definitions, function pointer variables, and function
pointer types from the same source data.
This can be useful for a shared library that you wish to dynamically open.


David Laight:

Home | Main Index | Thread Index | Old Index