Answer in brief
Conditional compilation includes or excludes source text according to preprocessing conditions.
Common directives
- #if tests a permitted preprocessing constant expression.
- #ifdef NAME checks whether NAME is defined.
- #ifndef NAME checks whether NAME is not defined.
- #elif and #else select alternative groups.
- #endif ends the conditional group.
Example explanation
The sample sets DEBUG to 1. #if DEBUG includes the debug message in the translated source, followed by the Ready message. If DEBUG were defined as 0, that debug line would be excluded. In contrast, #ifdef DEBUG would still succeed because the macro would remain defined.
Header guard
#ifndef CODEBHAVYA_SETTINGS_H
#define CODEBHAVYA_SETTINGS_H
/* declarations */
#endif
Why a guard is needed
The first inclusion defines the guard macro and includes the guarded contents. If the same header is included again in that translation unit, the macro already exists, so the contents are skipped. This prevents many repeated declarations or definitions from being processed incorrectly. It does not make an ordinary shared object definition safe to place in every source file; use suitable extern declarations.
Uses and precautions
Conditional compilation can select debug messages, optional features or platform-specific code. Use meaningful project-prefixed macro names and correctly pair each group with #endif. Do not use a runtime variable as though its value were available during preprocessing. A C const int object is not automatically a preprocessing macro or a permitted #if value.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define DEBUG 1
int main(void)
{
#if DEBUG
puts("Debug enabled");
#endif
puts("Ready");
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Debug enabled
Ready