C++ 전처리기 | "매크로" 고급 기법
이 글의 핵심
C++ 전처리기에 대한 실전 가이드입니다. 개념부터 실무 활용까지 예제와 함께 상세히 설명합니다.
기본 매크로
// 객체형 매크로
#define PI 3.14159
#define MAX_SIZE 100
// 함수형 매크로
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main() {
cout << PI << endl;
cout << SQUARE(5) << endl; // 25
cout << MAX(10, 20) << endl; // 20
}
조건부 컴파일
#ifdef DEBUG
#define LOG(msg) cout << "[DEBUG] " << msg << endl
#else
#define LOG(msg)
#endif
int main() {
LOG("프로그램 시작"); // DEBUG 정의 시만 출력
}
// 컴파일
// g++ -DDEBUG program.cpp
문자열화 (#)
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
int main() {
cout << STRINGIFY(hello) << endl; // "hello"
cout << TOSTRING(__LINE__) << endl; // "5"
}
토큰 붙이기 (##)
#define CONCAT(a, b) a##b
int main() {
int xy = 10;
cout << CONCAT(x, y) << endl; // xy → 10
}
실전 예시
예시 1: 디버그 매크로
#ifdef DEBUG
#define DEBUG_PRINT(fmt, ...) \
fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define DEBUG_PRINT(fmt, ...)
#endif
int main() {
int x = 10;
DEBUG_PRINT("x = %d", x);
// [main.cpp:12] x = 10
}
예시 2: X-Macro 패턴
// 에러 코드 정의
#define ERROR_CODES \
X(SUCCESS, 0, "성공") \
X(NOT_FOUND, 1, "찾을 수 없음") \
X(PERMISSION_DENIED, 2, "권한 없음") \
X(TIMEOUT, 3, "시간 초과")
// enum 생성
enum ErrorCode {
#define X(name, code, desc) name = code,
ERROR_CODES
#undef X
};
// 문자열 변환
const char* errorToString(ErrorCode code) {
switch (code) {
#define X(name, code, desc) case name: return desc;
ERROR_CODES
#undef X
default: return "알 수 없는 에러";
}
}
int main() {
cout << errorToString(NOT_FOUND) << endl; // "찾을 수 없음"
}
예시 3: 플랫폼별 코드
#ifdef _WIN32
#include <windows.h>
#define SLEEP(ms) Sleep(ms)
#else
#include <unistd.h>
#define SLEEP(ms) usleep((ms) * 1000)
#endif
int main() {
cout << "대기 중..." << endl;
SLEEP(1000); // 1초
cout << "완료" << endl;
}
예시 4: 버전 관리
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_PATCH 3
#define MAKE_VERSION(major, minor, patch) \
((major) * 10000 + (minor) * 100 + (patch))
#define VERSION MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH)
int main() {
cout << "버전: " << VERSION_MAJOR << "."
<< VERSION_MINOR << "." << VERSION_PATCH << endl;
#if VERSION >= 10200
cout << "새 기능 사용 가능" << endl;
#endif
}
가변 인자 매크로
// C++11
#define LOG(fmt, ...) \
printf("[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
int main() {
LOG("시작");
LOG("값: %d", 42);
LOG("값: %d, %s", 42, "test");
}
매크로 주의사항
1. 괄호 필수
// ❌ 위험
#define SQUARE(x) x * x
int result = SQUARE(2 + 3); // 2 + 3 * 2 + 3 = 11
// ✅ 괄호 사용
#define SQUARE(x) ((x) * (x))
int result = SQUARE(2 + 3); // (2 + 3) * (2 + 3) = 25
2. 부작용
// ❌ 부작용
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int x = 5;
int result = MAX(x++, 10); // x++가 두 번 실행될 수 있음!
// ✅ 함수 사용
template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}
3. 타입 안전성
// ❌ 타입 체크 없음
#define ADD(a, b) ((a) + (b))
ADD("hello", 10); // 컴파일 에러
// ✅ 템플릿 사용
template<typename T>
T add(T a, T b) {
return a + b;
}
유용한 매크로
컴파일 시간 정보
cout << "파일: " << __FILE__ << endl;
cout << "라인: " << __LINE__ << endl;
cout << "함수: " << __func__ << endl;
cout << "날짜: " << __DATE__ << endl;
cout << "시간: " << __TIME__ << endl;
static_assert 매크로
#define STATIC_ASSERT(cond, msg) \
static_assert(cond, msg)
STATIC_ASSERT(sizeof(int) == 4, "int는 4바이트여야 함");
디버그 매크로
#define ASSERT(cond) \
do { \
if (!(cond)) { \
fprintf(stderr, "Assertion failed: %s, %s:%d\n", \
#cond, __FILE__, __LINE__); \
abort(); \
} \
} while(0)
int main() {
int x = 10;
ASSERT(x > 0);
ASSERT(x < 5); // 실패
}
자주 발생하는 문제
문제 1: 세미콜론 문제
// ❌ 세미콜론 문제
#define LOG(msg) cout << msg << endl;
if (condition)
LOG("test");
else
cout << "else" << endl; // 에러!
// ✅ do-while 사용
#define LOG(msg) \
do { \
cout << msg << endl; \
} while(0)
문제 2: 매크로 재정의
// ❌ 재정의 경고
#define MAX 100
#define MAX 200 // 경고
// ✅ undef 후 재정의
#undef MAX
#define MAX 200
문제 3: 네임스페이스 오염
// ❌ 전역 네임스페이스 오염
#define SIZE 100
// ✅ 접두사 사용
#define MYLIB_SIZE 100
// ✅ constexpr 사용 (더 좋음)
constexpr int SIZE = 100;
매크로 vs 대안
// 매크로
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
// constexpr (권장)
constexpr double PI = 3.14159;
constexpr int square(int x) {
return x * x;
}
// inline 함수 (권장)
inline int square(int x) {
return x * x;
}
조건부 컴파일 패턴
// 플랫폼
#ifdef _WIN32
// Windows
#elif __linux__
// Linux
#elif __APPLE__
// macOS
#endif
// 컴파일러
#ifdef __GNUC__
// GCC
#elif _MSC_VER
// MSVC
#endif
// C++ 버전
#if __cplusplus >= 202002L
// C++20
#elif __cplusplus >= 201703L
// C++17
#endif
FAQ
Q1: 매크로는 언제 사용하나요?
A:
- 조건부 컴파일
- 디버그 로깅
- 플랫폼별 코드
Q2: 매크로 대신 무엇을 사용하나요?
A:
- constexpr (상수)
- inline 함수 (함수)
- 템플릿 (제네릭)
Q3: 매크로의 단점은?
A:
- 타입 체크 없음
- 디버깅 어려움
- 네임스페이스 오염
- 부작용 가능
Q4: X-Macro는 언제 사용하나요?
A: enum과 문자열 변환, 테이블 생성 등 반복적인 코드 생성.
Q5: 매크로 디버깅은?
A:
- -E 옵션으로 전처리 결과 확인
- Compiler Explorer
Q6: 전처리기 학습 리소스는?
A:
- GCC 전처리기 문서
- “C Preprocessor” (GNU)
- cppreference.com
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Macro Programming | “매크로 프로그래밍” 가이드
- C++ Preprocessor Directives | “전처리 지시자” 가이드
- C++ 전처리기 완벽 가이드 | #define·#ifdef
관련 글
- C++ 전처리기 완벽 가이드 | #define·#ifdef
- C++ 헤더 가드 완벽 가이드 | #ifndef vs #pragma once 실전 비교
- C++ Macro Programming |
- C++ Preprocessor Directives |
- C++ X-Macro 완벽 가이드 | enum-string 매핑·에러 코드·상태 머신·커맨드 테이블 실전