Use Conditional Compilation to Hide Platform Dependencies and Implement #include Guards (cont'd)
Conditional Compilation and Cross-platform Development
Every seasoned programmer is familiar with compiler-dependent quirks. For instance, a certain compiler treats char as an unsigned type, whereas another compiler treats it as a signed type. Similarly, long can be a 32-bit integer on one machine whereas on a 64-bit architecture it may be a 64-bit integer. To minimize the effects of such dependencies, use conditional compilation.
advertisement

During compilation, each compiler and operating system create predefined macros that identify various properties of the project's configuration. For example, if the project is configured for debug mode, the macro _DEBUG is automatically #defined. Similarly, you can define a platform-independent 32-bit integer like this:


#if defined (_IA64) //is it a 64-bit platform?
 typedef int INT32; //a 32-bit integer
#elif defined (_IA32) //else if
 typedef long INT32;
#else
 typedef long INT32; //default 
#endif // defined (_IA64)  
This set of conditions automatically declares the proper typedef for every environment. Consequently, the typedef name INT32 will refer to the correct datatype at compile time. The #elif directive standard for 'else if', whereas plain #else should be the last default case.

Necessity Is the Mother of All Macros
Many programming languages disposed of a preprocessor, believing they could offer more advanced facilities of source file configuration and portability. However, since C++ uses header files extensively and because it's used in diverse environments, conditional compilation is still an indispensable tool in every programmer's arsenal.

Previous Page: Demonstrating the Problem  
Danny Kalev is a system analyst and software engineer with 13 years of experience, specializing in C++ and object-oriented analysis and design. He is a member of the ANSI C++ standardization committee and the author of ANSI/ISO C++ Professional Programmer's Handbook (Que, 1999, ISBN: 0789720221).
Page 1: IntroductionPage 3: Conditional Compilation and Cross-platform Development
Page 2: Demonstrating the Problem