• C

Alternative to #ifdef ?

I work on a program which has a lot of files made by other programmers. Thi program is used for few different types of Siemens terminals and that's why
someone thought to use #ifdef statements inside the sources and now the sources looks very ugly and hard to be followed. Probably these statements were overused. My question is if the statemets can be reordered in blocks or something in order to make the code easier for debugging? Is there another alternative ?
Who is Participating?
Hi jori,
This is the common way for writing a multi-platform code.It is not always possible to group the code at macro level as it will create more redundancy.

e.g if a code has following lines
function f()
/*here comes the system call which has diff sementics on diff systems
#ifdef _UNIX
 Code ( Unix specific)
 other platform

Now one option is to write the function f as
#ifdef _UNIX

code for Unix


code for other platforms


This way code is more readable but the redundancy is very high.
That is main reason of putting only the statement or code chunk level macro usage.

There is one more option if repetative group of statements are encountered in the code.

#define UNIX 0
#define WINDOWS 1

#define CHANGE_SOCK(x,other param)
     case UNIX: ioctl(other param)
     case WINDOWS : ioctlsocket(other param)

These #defines can be in one .h file and you can use it to separate the platform dependent coding.But this is useful only
1) Difference in code is basically system call or logically grouped fixed code.
2) coding style is same i.e code flow is overall same for every platform.

Please get back for more clarifcation if required.


I dont really understand what you question is regarding the reordering,  but, if you would like to remove the #ifdefs, you could put your code under a source control system, and tag different version of it (one tag to see one version of the code, another one to see another version, etc..). I am only familiar with Clearcase as a source control system, and with Clearcase, you can set a view to see a certain version of the source. You could have your common code under the main branch (ie all view would see that code), and have the   code that is different in a branch, that way you dont have to maintain too many different version of the same code.

It you are stuck with all the #ifdefs, and you want to make sure that the defines are ok when u compile one version, you can use the #error prep directive, that will display an error and stop the compilation if you dont have the right defines.

If your program is not that critical to be real fast, you could rearrange the #ifdefs into conditional statements.
If C++ is an option for you you could use namespaces...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.