C Language: #ifdef Directive
This C tutorial explains how to use the #ifdef preprocessor directive in the C language.
Description
In the C Programming Language, the #ifdef directive allows for conditional compilation. The preprocessor determines if the provided macro exists before including the subsequent code in the compilation process.
Syntax
The syntax for the #ifdef directive in the C language is:
#ifdef macro_definition
- macro_definition
- The macro definition that must be defined for the preprocessor to include the C source code into the compiled application.
Note
- The #ifdef directive must be closed by an #endif directive.
Example
The following example shows how to use the #ifdef directive in the C language:
/* Example using #ifdef directive by TechOnTheNet.com */ #include <stdio.h> #define YEARS_OLD 10 int main() { #ifdef YEARS_OLD printf("TechOnTheNet is over %d years old.\n", YEARS_OLD); #endif printf("TechOnTheNet is a great resource.\n"); return 0; }
Here is the output of the executable program:
TechOnTheNet is over 10 years old. TechOnTheNet is a great resource.
A common use for the #ifdef directive is to enable the insertion of platform specific source code into a program.
The following is an example of this:
/* Example using #ifdef directive for inserting platform specific source code by TechOnTheNet.com */ #include <stdio.h> #define UNIX 1 int main() { #ifdef UNIX printf("UNIX specific function calls go here.\n"); #endif printf("TechOnTheNet is over 10 years old.\n"); return 0; }
The output of this program is:
UNIX specific function calls go here.
TechOnTheNet is over 10 years old.
In this example, the UNIX source code is enabled. To disable the UNIX source code, change the line #define UNIX 1
to #undef UNIX
.
Advertisements