C 預處理器

C 語言預處理器指令 (Preprocessor Directives) 參考。

#define

用於定義一個常量 (const) 或巨集 (macro)。

#define PI 3.14159
#define SQUARE(x) ((x)*(x))

#ifdef

如果 macro 已被定義,則編譯接下來的 code block。

#define DEBUG
#ifdef DEBUG
    printf("Debug mode is on\n");
#endif

#ifndef

如果 macro 未被定義,則編譯接下來的 code block。

通常與 #define 一起使用,以避免多重包含標頭文件。

#ifndef _MYHEADER_H
#define _MYHEADER_H
// 標頭文件內容
#endif

#include

用於包含其他 Header file。

#include <stdio.h>
#include "myheader.h"

#if / #else / #elif / #endif

根據給定的條件表達式,決定是否編譯接下來的 code block。

#if defined(_WIN32)
    // Windows 代碼
#elif defined(__linux__)
    // Linux 代碼
#else
    // 其他平台代碼
#endif

#undef

用於取消定義之前定義過的 macro

#define MAX 100
// 一些代碼
#undef MAX // 取消定義 MAX

#pragma

編譯器特定的指令,用於控制編譯器的行為。

#pragma once // 確保標頭文件只被包含一次 (替代 #ifndef trick)
#pragma omp parallel for // OpenMP 並行化 for 循環

#error

在預處理階段發出一條錯誤消息,通常用於檢測不滿足某些條件。

#if (__cplusplus < 201103L)
#error "This code requires C++11 or later"
#endif

#line

用於重新設置當前 source code 位置,主要用於 debug。