Conditional compilation


One of the most powerful features of the preprocessor is the so-called conditional compilation this  means that portions of the code could be excluded in the actual compilation under the certain conditions. 

This means that your source could contain special code for, say, the ARM processor. Using conditional  compilation, this code could be ignored when compiling for all other processors. 
The preprocessor directives #ifdef, #ifndef, #if, #elif, and #else are used to control the 
source code. 

The #ifdef (#ifndef) directive includes a section if a preprocessor symbol is defined 
(undefined). 



For example: 

#ifdef ARM_BUILD 
__ARM_do_something(); 
#else 
generic_do_something(); 
#endif 

The #if directive can handle any type of integer and logical expression, for example: 

#if (NUMBER_OF_PROCESSES > 1) && (LOCKING == TRUE) 

lock_process(); 
#endif 

The #elif directive works like a combined #else and #if. 
#if and #elif can use the special operator defined to check if a symbol is defined. This is useful in   combination with complex tests,

 for example: 
#if defined(VERSION) && (VERSION > 2) 
#endif 

In part two of this article we will revisit conditional compilation and discuss whether you should prefer 

#if:s or #ifdef:s in your application.

No comments:

Post a Comment