Post

Pre-processor C

Pre-processor C

✅ Những directive phổ biến trong C

DirectiveUse
#defineĐịnh nghĩa hằng số or macro
#undefHủy định nghĩa đã dùng #define
#includeThêm file header
#if, #elif, #else, #endifĐiều kiện compiler
#ifdef, #ifndefKiểm tra xem macro đã được định nghĩa hay chưa ?
#errorHiện thị lỗi khi compiler
#pragmaGửi chỉ dẫn đặc biệt tới compiler

🧪 Ví dụ 1: #if, #elif, #else, #endif

1
2
3
4
5
6
7
8
9
#define VERSION 2

#if VERSION == 1
    printf("Version 1\n");
#elif VERSION == 2
    printf("Version 2\n");
#else
    printf("Unknown version\n");
#endif

🧪 Ví dụ 2: #ifdef , #ifndef

1
2
3
4
5
6
7
8
9
#define DEBUG

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

#ifndef RELEASE
    printf("Not release mode\n");
#endif

🧪 Ví dụ 3: #error

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

#define VERSION 1

#ifndef VERSION
    #error "You need to define macro VERSION before compiler!"
#endif

int main() {
    printf("Version: %d\n", VERSION);
    return 0;
}

Output: Khi chưa #define VERSION 1

1
error: #error "You need to define macro VERSION before compiler!"

Reference

  • https://www.math.utah.edu/docs/info/cpp_1.html
  • https://en.wikipedia.org/wiki/C_preprocessor
This post is licensed under CC BY 4.0 by the author.