What is the complete list and usage scenarios of preprocessor directives in C language?
Core Preprocessor Directives:
-
File Inclusion #include
c#include <stdio.h> // System header #include "myheader.h" // User header // Conditional inclusion #if defined(USE_FEATURE) #include "feature.h" #endif -
Macro Definition #define
c// Simple macro #define PI 3.14159 #define MAX_SIZE 100 // Macro with parameters #define SQUARE(x) ((x) * (x)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) // Stringification #define STR(x) #x #define PRINT_VAR(var) printf(#var " = %d\n", var) // Token concatenation #define CONCAT(a, b) a##b -
Conditional Compilation
c#if defined(UNIX) #include <unistd.h> #elif defined(WINDOWS) #include <windows.h> #else #error "Unsupported platform" #endif #ifdef DEBUG #define LOG(x) printf x #else #define LOG(x) #endif -
Error and Warning
c#if SIZE < 0 #error "Size must be positive" #endif #if !defined(VERSION) #warning "VERSION not defined, using default" #define VERSION "1.0" #endif -
Line Control #line
c#line 100 "custom.c" // Error messages will show as custom.c:100 -
Compiler Directive #pragma
c#pragma once // Prevent multiple inclusion #pragma pack(1) // Memory alignment #pragma warning(disable:4996) // Disable warning -
Undefine #undef
c#define TEMP 100 #undef TEMP
Advanced Usage Scenarios:
-
Cross-platform Compatibility
c#if defined(_WIN32) || defined(_WIN64) #define PATH_SEPARATOR '\\' #else #define PATH_SEPARATOR '/' #endif -
Debug and Logging
c#ifdef DEBUG #define DEBUG_PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define DEBUG_PRINT(fmt, ...) #endif -
Version Control
c#define VERSION_MAJOR 2 #define VERSION_MINOR 5 #define VERSION_STRING "2.5"
Important Considerations:
- Macros have no type checking
- Macro expansion can cause unexpected side effects
- Prefer const and inline functions over macros