473,394 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

how to make elegant use of preprocessor directives

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
13 3540
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

"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
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
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
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
"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

"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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Jim Ford | last post by:
I have a single C file with the following code: int f2() { /* Blah-blah */ } int f1() { /* Blah-blah */
6
by: Urs Thuermann | last post by:
Does a tool exist to apply C preprocessor expansion to a C source only partially, i.e. replace only some directives? I want to replace some #if's by their expansions, e.g. all #ifdef SOME_SYMBOL,...
21
by: Bogdan | last post by:
Can anyone recommend a program for indentation of C preprocessor directives. My file looks like this: #ifdef a #define b #else #define c #endif int main() {
31
by: Sam of California | last post by:
Is it accurate to say that "the preprocessor is just a pass in the parsing of the source file"? I responded to that comment by saying that the preprocessor is not just a pass. It processes...
9
by: Bob | last post by:
Hi, Is it possible to change the references in a project by using preprocessor directives? Thanks, Bob
14
by: lagman | last post by:
All, I'm looking for a tool that is able to take my code base (which is full of preprocessor directives) and spit out source code that is "clean" of any preprocessor directives based on the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.