473,549 Members | 2,610 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3562
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*********@ya hoo.com> schrieb im Newsbeitrag
news:fd******** *************** ***@posting.goo gle.com...
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.f r> 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/[...]/vcrefPreprocess orReference.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.pow ernet.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******@netwa y.at> wrote in message news:<3f******* *************** *@newsreader01. highway.telekom .at>...
"seemanta dutta" <se*********@ya hoo.com> schrieb im Newsbeitrag
news:fd******** *************** ***@posting.goo gle.com...
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_HEADE R_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*********@ya hoo.com> schrieb im Newsbeitrag
news:26******** *************** ***@posting.goo gle.com...
"Robert Stankowic" <pc******@netwa y.at> wrote in message news:<3f******* *************** *@newsreader01. highway.telekom .at>...
"seemanta dutta" <se*********@ya hoo.com> schrieb im Newsbeitrag
news:fd******** *************** ***@posting.goo gle.com...
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_HEADE R_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.pow ernet.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**********@s parta.btinterne t.com>,
do******@addres s.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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1942
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
2420
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, but keep all other #ifdef OTHER_SYMBOL and all #include directives. urs
21
7608
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
2887
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 statements that the compiler does not process. The good people in the alt.comp.lang.learn.c-c++ newsgroup insist that the preprocessor is just one of...
9
2020
by: Bob | last post by:
Hi, Is it possible to change the references in a project by using preprocessor directives? Thanks, Bob
14
2576
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 options I choose (possibly via some kind of user input screen). Does such a tool exist? A Visual Studio plugin would be even better. FYI: I have...
0
7464
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7979
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7497
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6065
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5385
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3512
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1960
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1074
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
781
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.