乐闻世界logo
搜索文章和话题

What is the complete list and usage scenarios of preprocessor directives in C language?

2月18日 17:21

What is the complete list and usage scenarios of preprocessor directives in C language?

Core Preprocessor Directives:

  1. File Inclusion #include

    c
    #include <stdio.h> // System header #include "myheader.h" // User header // Conditional inclusion #if defined(USE_FEATURE) #include "feature.h" #endif
  2. 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
  3. 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
  4. 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
  5. Line Control #line

    c
    #line 100 "custom.c" // Error messages will show as custom.c:100
  6. Compiler Directive #pragma

    c
    #pragma once // Prevent multiple inclusion #pragma pack(1) // Memory alignment #pragma warning(disable:4996) // Disable warning
  7. Undefine #undef

    c
    #define TEMP 100 #undef TEMP

Advanced Usage Scenarios:

  1. Cross-platform Compatibility

    c
    #if defined(_WIN32) || defined(_WIN64) #define PATH_SEPARATOR '\\' #else #define PATH_SEPARATOR '/' #endif
  2. Debug and Logging

    c
    #ifdef DEBUG #define DEBUG_PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define DEBUG_PRINT(fmt, ...) #endif
  3. 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
标签:C语言