LF Tip: #defines for writing portable C-code



AuthorImage:[Here we need a little image from you]

[Photo of the Author]

TranslationInfo:[Author + translation history. mailto: or http://homepage]

original in en Guido Socher

AboutTheAuthor:[A small biography about the author]

Guido really likes it when a computer is tailored to his needs and looks like he wants it. That's why he is using Linux.


This is a small tip. From now on LinuxFocus will have at least one new tip every month. If you have some ideas for a new tip then send them to guido("at" sign)linuxfocus.org





Java is known as "write once works never" and C is "write once, compile and works always". In other words C code is very portable and the beauty is also that you can have preprocessor #ifdef statements to distinguish between the different platforms. This way you have just one piece of code which can be recompiled on different systems even without running an auto configuration script before compilation.

Here is an example:
#ifdef sun
	// solaris
static char *port="/dev/ttya";

#ifdef linux
	// linux
static char *port="/dev/ttyS0";

What #define is available?

The question is only how do you know that there is a #define linux or __linux__? ... and what other #defines do we have?

It's quite simple. Just run this command and you get a list of pre-defined #define statements:
 touch /tmp/foo.h ; cpp -dM /tmp/foo.h
That's all.