By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,413 Members | 999 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,413 IT Pros & Developers. It's quick & easy.

how to make elegant use of preprocessor directives

P: n/a
Greetings C gurus,
I have used preprocessor directives since a very long time. But
whenever I see some professional piece of C code, the linux kernel for
example, I get literally confused by the amount of preprocessor
directives used in these code.

Can anyone please tell me how to actually use these preprocessor
directives in a more professional way like selecting particular lines
of code suited for some particular hardware etc...

I always wonder what all these directives do in the source code.
So please can anyone help me in grasping the finer details of using
preprocessor directives to their maximum potential so that
professional C code no longer looks arcane to me.

thanks in advance
regards,
Seemanta Dutta
Nov 13 '05 #1
Share this Question
Share on Google+
13 Replies


P: n/a
seemanta dutta wrote:
Greetings C gurus,
I'm not one, and you're probably a better C coder than me, but...
I have used preprocessor directives since a very long time. But
whenever I see some professional piece of C code, the linux kernel for
example,
Err... Is this the best exemple ? (dont take it wrong, I'm an - happy -
linux user, and I wouldn't be able to read or understand, let alone
writing, such code... But I'm not sure it qualifies as a an exemple of
clean C code).
I get literally confused by the amount of preprocessor
directives used in these code.
I do to. Hence the doubt expressed above...
Can anyone please tell me how to actually use these preprocessor
directives in a more professional way like selecting particular lines
of code suited for some particular hardware etc...
I'd say that the most professionnal way to do it is to put
platform-dependant code in separate modules, and to selectively include
and/or link the appropriate modules. The core logic should be readable
and understandable without having to worry about the target platform IMHO.
I always wonder what all these directives do in the source code.
I do to. IMHO source code full of preprocessor directives is bad code.
So please can anyone help me in grasping the finer details of using
preprocessor directives to their maximum potential so that
professional C code no longer looks arcane to me.


Truly professional-quality [C or whatever] code should not look arcane
for an average [C or whatever] programmer, unless the algorithm is by
itself complex - and it then should be clearly documented.
Professionalism is about writing functionnal and maintainable code, not
half-obfuscated code relying on voodoo tricks. I personnaly think that
true simplicity is a virtue.

Now since I would certainly not pretend being a C guru, it may just
happens that what I view as complicated and obfuscated would seems
crystal clear to a good C programmer !-)

My 2 cents
Bruno

Nov 13 '05 #2

P: n/a

"seemanta dutta" <se*********@yahoo.com> schrieb im Newsbeitrag
news:fd**************************@posting.google.c om...
Greetings C gurus,
I have used preprocessor directives since a very long time. But
whenever I see some professional piece of C code, the linux kernel for
example, I get literally confused by the amount of preprocessor
directives used in these code.

Can anyone please tell me how to actually use these preprocessor
directives in a more professional way like selecting particular lines
of code suited for some particular hardware etc...

I always wonder what all these directives do in the source code.
So please can anyone help me in grasping the finer details of using
preprocessor directives to their maximum potential so that
professional C code no longer looks arcane to me.


I absolutely dislike code cluttered with #ifdef, #ifndef etc., especially if
those blocks are nested. IMHO it is bad practice to stuff al the variations
for a zillion of different systems into one piece of code, and if it cannot
be avoided it should be at least organized so, that larger pieces of code
are enclosed in #ifdef blocks, even at the price of more lines.

I also don't like the redefinition of basic types (WORD, DWORD for example),
but I understand, that this methid _might_ make the migration from one
version of a system to the next easier.

Just my $ 0.02
Robert
Nov 13 '05 #3

P: n/a
Bruno Desthuilliers <bd***********@removeme.free.fr> wrote in message news:<3f***********************@news.free.fr>...
seemanta dutta wrote:
I have used preprocessor directives since a very long time. But
whenever I see some professional piece of C code, the linux kernel for
example,
I get literally confused by the amount of preprocessor
directives used in these code.
Can anyone please tell me how to actually use these preprocessor
directives in a more professional way like selecting particular lines
of code suited for some particular hardware etc...
I'd say that the most professionnal way to do it is to put
platform-dependant code in separate modules, and to selectively include
and/or link the appropriate modules. The core logic should be readable
and understandable without having to worry about the target platform IMHO.


I concur. The core logic to impelement a task can even be done in a
different language from the implementation of the machine-dependent
code. (Implementing the core code in C and the hardware-specific code
in assembly, for example, or even writing the core code in Python and
the system-specific code in C.)

Of course, sometimes a finer grain of control is needed. Dividing your
code up should be done on a logical basis, not simply to dike out the
machine-specific stuff (they do not always coincide).
I always wonder what all these directives do in the source code.
I do to. IMHO source code full of preprocessor directives is bad code.


#include statements are preprocessor directives. ;) I think you mean
code full of conditional compliation directives is bad code. On that,
I agree as well.

Conditional compilation can be used to remove sections of code that
are not relevant to a given environment but cannot be excised into
their own subroutines all the time. Not adding irrelevant sections to
a binary can reduce the size of the resulting program immensely, but
simply cutting the size shouldn't be a prime concern (usually).

In any case, any tool can be misused and any tool can be overused. The
C preprocessor is just complex enough to do the job it was built to do
and it does that job well. Using it to decide the logic of a program
is wrong, and using it to the exclusion of more elegant solutions is
also wrong.
So please can anyone help me in grasping the finer details of using
preprocessor directives to their maximum potential so that
professional C code no longer looks arcane to me.
Truly professional-quality [C or whatever] code should not look arcane
for an average [C or whatever] programmer, unless the algorithm is by
itself complex - and it then should be clearly documented.


I again agree. I also have a small caveat: If the algoritm becomes too
complex, some of the complexity may be shifted to the data the
algorithm processes. In my experience, a well-designed data format can
reduce the complexity of algorithms immensely.
Professionalism is about writing functionnal and maintainable code, not
half-obfuscated code relying on voodoo tricks. I personnaly think that
true simplicity is a virtue.
Yep. Simplicity is a virtue. I think a lot of programmers who create
voodoo code are trying to `optimize' certain areas that, like as not,
don't need to be optimized. Premature optimization is a great evil.
Optimization in general should only be done if it needs to be, and
only after the performance of each section of code has been carefully
measured.

That, or they're trying to win the IOCCC. ;)

Now since I would certainly not pretend being a C guru, it may just
happens that what I view as complicated and obfuscated would seems
crystal clear to a good C programmer !-)
Heh. Usually not: Everyone's short-term memory can only hold an
average of seven items, plus or minus one. Code asking us to memorize
more causes an overflow condition and forces us to think much harder.
If code is confusing to an average C programmer, it's probably only
marginally more comprehenisble to a guru.

My 2 cents
Bruno

Nov 13 '05 #4

P: n/a
Have a look at the C Preprocessor reference.

http://msdn.microsoft.com/library/de...rReference.asp

Sandeep
--
http://www.EventHelix.com/EventStudio
EventStudio 2.0 - System Architecture Design CASE Tool
Nov 13 '05 #5

P: n/a
EventHelix.com wrote:
Have a look at the C Preprocessor reference.

http://msdn.microsoft.com/[...]/vcrefPreprocessorReference.asp

That is not *the* C Preprocessor reference. It is merely *a* C Preprocessor
reference, and it is certainly not authoritative. *The* C Preprocessor
reference is to be found in ISO/IEC 9899, and is most definitely
authoritative.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #6

P: n/a
"Robert Stankowic" <pc******@netway.at> wrote in message news:<3f***********************@newsreader01.highw ay.telekom.at>...
"seemanta dutta" <se*********@yahoo.com> schrieb im Newsbeitrag
news:fd**************************@posting.google.c om...
I have used preprocessor directives since a very long time. But
... I get literally confused by the amount of preprocessor
directives used in these code.
I absolutely dislike code cluttered with #ifdef, #ifndef etc., especially if
those blocks are nested.


Some standard libraries are full of macros named _FOOBAR, __FOOBAR,
___FOOBAR_, etc., reminding me of that old computer maze from the 1970's:
"twisty turny passages, all alike."

I just tried this on a RedHat system:
ln -s /dev/tty{,.c}
gcc -E /dev/tty.c
#include <stdio.h>
^D
Would you believe 920 lines of output, from 17 distinct header files!!!
That's header files actually read, not those bypassed because __FOOBAR
was set instead of _FOOBAR__. And I'm sure many of the 17 were read
multiple times but bypassed because of the lines
#ifndef __WEVE_ALREADY_READ_THIS_HEADER_TOO_OFTEN

I realize all the macros and declarations are purposeful, and that
today's machine can whip through that silliness millions of times
while I'm writing this gripe, but it still offends my sense of beauty
and love of simplicity.

Frankly, I often just write "extern int *stderr;", or whatever I need,
instead of "#include <stdio.h>". (I only do this in the privacy of my
own boudoir and will claim this posting was forged if push comes to shove.)

I was attracted to Programming as a form of Poetry, but today's methods
would run "Ode to a Skylark" through a grammar checker and make it
look like a military spec.
My 2 cents
Bruno
Just my $ 0.02
Robert


I'd be happy to contribute a few pennies too, but I'm afraid returning
to software elegance may have as much chance as saving the Dodo birds.

James

Disclaimer: One of my programs ended up with so many nested ifdef's
it was disgusting. I always viewed them as temporary, but never got
around to cleaning them up ... because they were too unpleasant to look at!
Nov 13 '05 #7

P: n/a

"James Dow Allen" <jd*********@yahoo.com> schrieb im Newsbeitrag
news:26**************************@posting.google.c om...
"Robert Stankowic" <pc******@netway.at> wrote in message news:<3f***********************@newsreader01.highw ay.telekom.at>...
"seemanta dutta" <se*********@yahoo.com> schrieb im Newsbeitrag
news:fd**************************@posting.google.c om...
I have used preprocessor directives since a very long time. But
... I get literally confused by the amount of preprocessor
directives used in these code.


I absolutely dislike code cluttered with #ifdef, #ifndef etc., especially if those blocks are nested.


Some standard libraries are full of macros named _FOOBAR, __FOOBAR,
___FOOBAR_, etc., reminding me of that old computer maze from the 1970's:
"twisty turny passages, all alike."

I just tried this on a RedHat system:
ln -s /dev/tty{,.c}
gcc -E /dev/tty.c
#include <stdio.h>
^D
Would you believe 920 lines of output, from 17 distinct header files!!!
That's header files actually read, not those bypassed because __FOOBAR
was set instead of _FOOBAR__. And I'm sure many of the 17 were read
multiple times but bypassed because of the lines
#ifndef __WEVE_ALREADY_READ_THIS_HEADER_TOO_OFTEN

I realize all the macros and declarations are purposeful, and that
today's machine can whip through that silliness millions of times
while I'm writing this gripe, but it still offends my sense of beauty
and love of simplicity.


Well, I am not bothered about this stuff in standard headers, normally there
should be no need to look at them at all, they are delvered by the
implementer of the standard libraries and usually you can trust that the
implementer got it right (And I am not supposed to maintain them). :)
But i hate application code cluttered with all kinds of conditional
compilation, which I _have to_ maintain, which means I have to dig through
that mess or at least use some tool which preprocesses that stuff

Frankly, I often just write "extern int *stderr;", or whatever I need,
instead of "#include <stdio.h>". (I only do this in the privacy of my
own boudoir and will claim this posting was forged if push comes to shove.)

I would not go that far, for me that is too much error prone, but YMMV

I was attracted to Programming as a form of Poetry, but today's methods
would run "Ode to a Skylark" through a grammar checker and make it
look like a military spec.


Have you ever had a look at the source code of the good old (Univac) OS1100
? :)

Robert
Nov 13 '05 #8

P: n/a
James Dow Allen wrote:

<snip>
I was attracted to Programming as a form of Poetry, but today's methods
would run "Ode to a Skylark" through a grammar checker and make it
look like a military spec.

I'd be happy to contribute a few pennies too, but I'm afraid returning
to software elegance may have as much chance as saving the Dodo birds.


This chimes perfectly with my own attitude to programming. I don't always
succeed in making my programs elegant, but I always /try/. I certainly
agree that reducing the number of #ifs and #ifdefs is a worthy goal,
because they look ugly and break the reader's flow. (Obviously, there is a
place for them - for example, inclusion guards.)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #9

P: n/a
In article <bq**********@sparta.btinternet.com>,
do******@address.co.uk.invalid says...
This chimes perfectly with my own attitude to programming. I don't always
succeed in making my programs elegant, but I always /try/. I certainly
agree that reducing the number of #ifs and #ifdefs is a worthy goal,
because they look ugly and break the reader's flow. (Obviously, there is a
place for them - for example, inclusion guards.)


Another place this comes up is when you are inevitably forced to write
some platform dependent code. By burying the "ugly bits" in a file that
hides the detail from one platform to the next behind a higher level
generic interface so that the rest of your code does NOT have to know
about those things, a few ifdef's in that module seem rather clean
compared to some of the alternatives.
--
Randy Howard _o
2reply remove FOOBAR \<,
______________________()/ ()______________________________________________
SCO Spam-magnet: po********@sco.com
Nov 13 '05 #10

P: n/a
Randy Howard wrote:
In article <bq**********@sparta.btinternet.com>,
do******@address.co.uk.invalid says...
This chimes perfectly with my own attitude to programming. I don't always
succeed in making my programs elegant, but I always /try/. I certainly
agree that reducing the number of #ifs and #ifdefs is a worthy goal,
because they look ugly and break the reader's flow. (Obviously, there is
a place for them - for example, inclusion guards.)


Another place this comes up is when you are inevitably forced to write
some platform dependent code. By burying the "ugly bits" in a file that
hides the detail from one platform to the next behind a higher level
generic interface so that the rest of your code does NOT have to know
about those things, a few ifdef's in that module seem rather clean
compared to some of the alternatives.


Well, that's one way to do it, and a perfectly valid way. Another way, and
one that involves rather less #ifing around (but, on the downside, better
file management) is to (a) modularise as you propose, and then (b) have a
different foo.c for each platform. (If you're useless at file management,
this is a really *bad* way to do things. If you can keep it all straight,
though, it's very neat.)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #11

P: n/a
se*********@yahoo.com (seemanta dutta) wrote in message news:<fd**************************@posting.google. com>...
Greetings C gurus,
May the rest of us respond too :-) ??
I have used preprocessor directives since a very long time. But
whenever I see some professional piece of C code, the linux kernel for
example, I get literally confused by the amount of preprocessor
directives used in these code.
As someone else noted, the linux kernel is hardly the neatest
piece of code on the planet.

Can anyone please tell me how to actually use these preprocessor
directives in a more professional way like selecting particular lines
of code suited for some particular hardware etc...
You should not do this. Is it not possible to encapsulate your
hardware specific routines in its own module ?

I always wonder what all these directives do in the source code.
So please can anyone help me in grasping the finer details of using
preprocessor directives to their maximum potential so that
professional C code no longer looks arcane to me.


dunno about anyone else, but I never use preprocessor directives
in my source (as opposed to header[1]) files, with one exception;
Lengthy switch statements for my "diagnostic" routines. for example
the platform I work on now has an OS and various OS-functions that
are callable by applications (OS_MemMalloc(), OS_FileOpen(), etc).

All OS functions return a status code of type enum OS_STATUS. one of
these return codes is OS_OK. while it is nice to be able to
abort on error (OS_NO_MEM), it is even nicer to abort *and* print
the reason for doing so. thus I made a function like so

char *os_status_to_english (OS_STATUS the_status) {
switch (the_status) {
#define CASE_STATUS(status) case status: return #status
CASE_STATUS (OS_OK);
CASE_STATUS (OS_NO_MEM);
CASE_STATUS (OS_HEAP_ERROR);
CASE_STATUS (OS_DENIED);
...
/* all enum types */
default: return "unknown os error";
#undef CASE_STATUS
}
}

in usage, I've got a macro that prints a
string to the printer:

....
OS_STATUS retcode = OS_SomeFunc();
....
if (retcode!=OS_OK) {
PRINT_ERROR (os_status_to_english (retcode));
/* handle rest of error here */
}
....
[1]. safeguards, mostly, but also very helpfull for
diagnostic macros that include the __LINE__ and __FILE__
macros.

other than that example above, I dont recall using
many directives in actual code, mostly in headers.
hth
goose,
Nov 13 '05 #12

P: n/a
In <bq**********@titan.btinternet.com> Richard Heathfield <do******@address.co.uk.invalid> writes:
Randy Howard wrote:
In article <bq**********@sparta.btinternet.com>,
do******@address.co.uk.invalid says...
This chimes perfectly with my own attitude to programming. I don't always
succeed in making my programs elegant, but I always /try/. I certainly
agree that reducing the number of #ifs and #ifdefs is a worthy goal,
because they look ugly and break the reader's flow. (Obviously, there is
a place for them - for example, inclusion guards.)


Another place this comes up is when you are inevitably forced to write
some platform dependent code. By burying the "ugly bits" in a file that
hides the detail from one platform to the next behind a higher level
generic interface so that the rest of your code does NOT have to know
about those things, a few ifdef's in that module seem rather clean
compared to some of the alternatives.


Well, that's one way to do it, and a perfectly valid way. Another way, and
one that involves rather less #ifing around (but, on the downside, better
file management) is to (a) modularise as you propose, and then (b) have a
different foo.c for each platform. (If you're useless at file management,
this is a really *bad* way to do things. If you can keep it all straight,
though, it's very neat.)


Not very practical when about 90% of the code is common, but the
remaining 10% are interspersed all over the place and practically
impossible to isolate. If you create separate files (differing only in
the 10% bits), all changes to the common code base would have to be
replicated to all the files, which is a significant maintenance overhead.

#ifdef's are ugly, but the costs of avoiding them often make them the
optimal solution.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #13

P: n/a
In article <bq**********@titan.btinternet.com>,
do******@address.co.uk.invalid says...
Randy Howard wrote:
Another place this comes up is when you are inevitably forced to write
some platform dependent code. By burying the "ugly bits" in a file that
hides the detail from one platform to the next behind a higher level
generic interface so that the rest of your code does NOT have to know
about those things, a few ifdef's in that module seem rather clean
compared to some of the alternatives.


Well, that's one way to do it, and a perfectly valid way. Another way, and
one that involves rather less #ifing around (but, on the downside, better
file management) is to (a) modularise as you propose, and then (b) have a
different foo.c for each platform. (If you're useless at file management,
this is a really *bad* way to do things. If you can keep it all straight,
though, it's very neat.)


Well, that's surely another common method. I was thinking of a much
smaller amount of code than what I *think* you are describing above. If
the amount of "#ifing" can be fit into a single file of about the same
size as a normal source module, I don't think it's all that ugly. On the
other hand, if you're really diving off into a lot of platform dependent
code, then I agree with what you're saying. Having for example a tree of
source files, with a group for each target platform to provide those non-
portable bits seems to be an often used convention.

--
Randy Howard _o
2reply remove FOOBAR \<,
______________________()/ ()______________________________________________
SCO Spam-magnet: po********@sco.com
Nov 13 '05 #14

This discussion thread is closed

Replies have been disabled for this discussion.