Module 15: Preprocessor & Macro

Preprocessor trong C

#define - Định nghĩa hằng và macro

#define PI 3.14159
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define SQUARE(x) ((x)*(x))

Toán tử trong macro

#define STR(x) #x        // bien thanh chuoi
#define CONCAT(a,b) a##b // noi token

Điều kiện biên dịch

#ifdef DEBUG
    printf("x = %d\n", x);
#endif

#ifndef HEADER_H
#define HEADER_H
// header file content
#endif

#pragma

#pragma once  // tranh include nhieu lan
#pragma pack(1) // align struct

Macro vs Function

  • Macro: nhanh, không kiểm tra kiểu, khó debug
  • Function: chậm hơn (call overhead), an toàn kiểu

predefined macros

__LINE__  // dong hien tai
__FILE__  // file hien tai
__DATE__  // ngay bien dich
__TIME__  // gio bien dich