Browse DevX
Sign up for e-mail newsletters from DevX


Use Conditional Compilation to Hide Platform Dependencies and Implement #include Guards-3 : Page 3




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

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.

Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date