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

C语言中预处理器指令的完整列表和使用场景有哪些?

2月18日 17:21

C语言中预处理器指令的完整列表和使用场景有哪些?

核心预处理器指令:

  1. 文件包含 #include

    c
    #include <stdio.h> // 系统头文件 #include "myheader.h" // 用户头文件 // 条件包含 #if defined(USE_FEATURE) #include "feature.h" #endif
  2. 宏定义 #define

    c
    // 简单宏 #define PI 3.14159 #define MAX_SIZE 100 // 带参数的宏 #define SQUARE(x) ((x) * (x)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) // 字符串化 #define STR(x) #x #define PRINT_VAR(var) printf(#var " = %d\n", var) // 连接 #define CONCAT(a, b) a##b
  3. 条件编译

    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. 错误和警告

    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

    c
    #line 100 "custom.c" // 错误信息将显示为 custom.c:100
  6. 编译指示 #pragma

    c
    #pragma once // 防止重复包含 #pragma pack(1) // 内存对齐 #pragma warning(disable:4996) // 禁用警告
  7. 取消定义 #undef

    c
    #define TEMP 100 #undef TEMP

高级应用场景:

  1. 跨平台兼容性

    c
    #if defined(_WIN32) || defined(_WIN64) #define PATH_SEPARATOR '\\' #else #define PATH_SEPARATOR '/' #endif
  2. 调试和日志

    c
    #ifdef DEBUG #define DEBUG_PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define DEBUG_PRINT(fmt, ...) #endif
  3. 版本控制

    c
    #define VERSION_MAJOR 2 #define VERSION_MINOR 5 #define VERSION_STRING "2.5"

注意事项:

  • 宏没有类型检查
  • 宏展开可能导致意外的副作用
  • 优先使用 const 和 inline 函数替代宏
标签:C语言