C++ Preprocessor Directives | "전처리 지시자" 가이드
이 글의 핵심
C++ Preprocessor Directives에 대한 실전 가이드입니다.
전처리 지시자란?
전처리 지시자 (Preprocessor Directives) 는 컴파일 전에 처리되는 명령어로, #으로 시작합니다. 파일 포함, 매크로 정의, 조건부 컴파일 등에 사용됩니다.
#include <iostream> // 파일 포함
#define MAX 100 // 매크로 정의
#ifdef DEBUG // 조건부 컴파일
// 디버그 코드
#endif
왜 필요한가?:
- 파일 포함: 헤더 파일 통합
- 조건부 컴파일: 플랫폼별 코드
- 매크로 정의: 상수, 함수 대체
- 빌드 설정: 디버그/릴리스 구분
// ❌ 전처리 없이: 중복 코드
// file1.cpp
void func() {
#ifdef DEBUG
std::cout << "디버그\n";
#endif
}
// file2.cpp
void func2() {
#ifdef DEBUG
std::cout << "디버그\n";
#endif
}
// ✅ 전처리 사용: 중앙 관리
// config.h
#ifdef DEBUG
#define LOG(x) std::cout << x << '\n'
#else
#define LOG(x)
#endif
// file1.cpp, file2.cpp
LOG("디버그");
전처리 단계:
flowchart LR
A[소스 코드] --> B[전처리기]
B --> C[전처리된 코드]
C --> D[컴파일러]
D --> E[어셈블리]
E --> F[링커]
F --> G[실행 파일]
전처리 순서:
- 파일 포함 (
#include) - 매크로 확장 (
#define) - 조건부 컴파일 (
#ifdef,#if) - 기타 지시자 (
#pragma,#error)
전처리 결과 확인:
# GCC/Clang
g++ -E file.cpp -o file.i
# MSVC
cl /E file.cpp
주요 지시자
// 1. #include
#include <iostream> // 시스템 헤더
#include "myheader.h" // 사용자 헤더
// 2. #define
#define PI 3.14
#define MAX(a,b) ((a)>(b)?(a):(b))
// 3. #undef
#undef MAX
// 4. #ifdef, #ifndef
#ifdef DEBUG
#define LOG(x) std::cout << x
#else
#define LOG(x)
#endif
// 5. #if, #elif, #else
#if VERSION >= 2
// 버전 2 이상
#elif VERSION == 1
// 버전 1
#else
// 그 외
#endif
// 6. #pragma
#pragma once
#pragma pack(1)
실전 예시
예시 1: 인클루드 가드
// myheader.h
#ifndef MYHEADER_H
#define MYHEADER_H
class MyClass {
// ...
};
#endif
// 또는 #pragma once
#pragma once
class MyClass {
// ...
};
예시 2: 조건부 컴파일
// config.h
#define DEBUG_MODE 1
#define PLATFORM_WINDOWS 1
// main.cpp
#include "config.h"
#if DEBUG_MODE
#define LOG(x) std::cout << "[DEBUG] " << x << std::endl
#else
#define LOG(x)
#endif
#ifdef PLATFORM_WINDOWS
#include <windows.h>
#elif defined(PLATFORM_LINUX)
#include <unistd.h>
#endif
int main() {
LOG("프로그램 시작");
}
예시 3: 매크로 함수
#define SQUARE(x) ((x) * (x))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
int main() {
int x = SQUARE(5); // 25
int max = MAX(10, 20); // 20
int min = MIN(10, 20); // 10
}
예시 4: 문자열화
#define STRINGIFY(x) #x
#define CONCAT(a,b) a##b
int main() {
std::cout << STRINGIFY(Hello) << std::endl; // "Hello"
int xy = 10;
int result = CONCAT(x, y); // xy
}
조건부 컴파일
// 플랫폼별
#ifdef _WIN32
// Windows 코드
#elif defined(__linux__)
// Linux 코드
#elif defined(__APPLE__)
// macOS 코드
#endif
// 컴파일러별
#ifdef __GNUC__
// GCC 코드
#elif defined(_MSC_VER)
// MSVC 코드
#endif
// 디버그/릴리스
#ifdef NDEBUG
// 릴리스 코드
#else
// 디버그 코드
#endif
자주 발생하는 문제
문제 1: 매크로 부작용
// ❌ 부작용
#define SQUARE(x) x * x
int result = SQUARE(1 + 2); // 1 + 2 * 1 + 2 = 5
// ✅ 괄호 사용
#define SQUARE(x) ((x) * (x))
int result = SQUARE(1 + 2); // 9
문제 2: 인클루드 가드 누락
// ❌ 가드 없음
// myheader.h
class MyClass {};
// ✅ 가드 추가
#ifndef MYHEADER_H
#define MYHEADER_H
class MyClass {};
#endif
문제 3: 매크로 vs 함수
// ❌ 매크로 (타입 안전하지 않음)
#define MAX(a,b) ((a)>(b)?(a):(b))
// ✅ 템플릿 함수
template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}
문제 4: #pragma once vs 가드
// #pragma once (간단)
#pragma once
class MyClass {};
// 인클루드 가드 (표준)
#ifndef MYHEADER_H
#define MYHEADER_H
class MyClass {};
#endif
#pragma 지시자
// 1. #pragma once
#pragma once
// 2. #pragma pack
#pragma pack(push, 1)
struct Data {
char c;
int i;
};
#pragma pack(pop)
// 3. #pragma warning
#pragma warning(disable: 4996)
// 4. #pragma message
#pragma message("컴파일 메시지")
// 5. #pragma omp (OpenMP)
#pragma omp parallel for
for (int i = 0; i < 100; i++) {
// 병렬 처리
}
실무 패턴
패턴 1: 플랫폼 추상화
// platform.h
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#define PATH_SEP '\\'
#include <windows.h>
#elif defined(__linux__)
#define EXPORT __attribute__((visibility("default")))
#define PATH_SEP '/'
#include <unistd.h>
#elif defined(__APPLE__)
#define EXPORT __attribute__((visibility("default")))
#define PATH_SEP '/'
#include <TargetConditionals.h>
#endif
// 사용
EXPORT void myFunction() {
std::string path = "dir" + std::string(1, PATH_SEP) + "file.txt";
}
패턴 2: 디버그 로깅
// debug.h
#ifdef DEBUG
#define LOG(level, msg) \
std::cout << "[" << level << "] " << __FILE__ << ":" << __LINE__ \
<< " " << msg << '\n'
#define ASSERT(cond) \
if (!(cond)) { \
std::cerr << "Assertion failed: " #cond << '\n'; \
std::abort(); \
}
#else
#define LOG(level, msg)
#define ASSERT(cond)
#endif
// 사용
void processData(int* data, size_t size) {
ASSERT(data != nullptr);
ASSERT(size > 0);
LOG("INFO", "Processing " << size << " items");
// ...
}
패턴 3: 버전 관리
// version.h
#define VERSION_MAJOR 2
#define VERSION_MINOR 3
#define VERSION_PATCH 1
#if VERSION_MAJOR >= 2
#define HAS_NEW_FEATURE 1
#endif
// api.cpp
void useAPI() {
#ifdef HAS_NEW_FEATURE
// 새 기능 사용
newFeature();
#else
// 구버전 호환
oldFeature();
#endif
}
FAQ
Q1: 전처리 지시자는 언제 사용하나요?
A:
- 파일 포함:
#include로 헤더 통합 - 조건부 컴파일: 플랫폼별 코드
- 매크로 정의: 상수, 함수 대체
#include <iostream>
#define MAX 100
#ifdef DEBUG
#define LOG(x) std::cout << x
#endif
Q2: #pragma once vs 인클루드 가드?
A:
#pragma once: 간단, 빠름 (비표준)- 인클루드 가드: 표준, 호환성
// #pragma once
#pragma once
class MyClass {};
// 인클루드 가드
#ifndef MYHEADER_H
#define MYHEADER_H
class MyClass {};
#endif
Q3: 매크로 vs 함수?
A:
- 매크로: 전처리, 타입 무관, 디버깅 어려움
- 함수: 타입 안전, 디버깅 가능
// ❌ 매크로: 타입 안전하지 않음
#define MAX(a,b) ((a)>(b)?(a):(b))
// ✅ 템플릿 함수: 타입 안전
template<typename T>
T max(T a, T b) { return a > b ? a : b; }
Q4: #ifdef vs #if defined?
A:
#ifdef: 간단한 조건#if defined: 복잡한 조건
// 간단
#ifdef DEBUG
// ...
#endif
// 복잡
#if defined(DEBUG) && defined(VERBOSE)
// ...
#endif
Q5: 전처리 결과를 확인하려면?
A: g++ -E file.cpp 또는 **cl /E file.cpp**를 사용합니다.
# GCC/Clang
g++ -E main.cpp -o main.i
# MSVC
cl /E main.cpp > main.i
Q6: 매크로의 부작용을 방지하려면?
A: 괄호를 충분히 사용합니다.
// ❌ 부작용
#define SQUARE(x) x * x
SQUARE(1 + 2); // 1 + 2 * 1 + 2 = 5
// ✅ 괄호 사용
#define SQUARE(x) ((x) * (x))
SQUARE(1 + 2); // 9
Q7: 매크로를 디버깅하려면?
A: **#error와 #warning**을 사용합니다.
#ifndef VERSION
#error "VERSION is not defined"
#endif
#if VERSION < 2
#warning "Old version detected"
#endif
Q8: 전처리 지시자 학습 리소스는?
A:
- “C++ Primer” by Stanley Lippman
- GCC Preprocessor Documentation
- cppreference.com - Preprocessor
관련 글: macro, pragma, include.
한 줄 요약: 전처리 지시자는 컴파일 전에 처리되는 명령어로, 파일 포함, 매크로 정의, 조건부 컴파일에 사용됩니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ 전처리기 | “매크로” 고급 기법
- C++ 헤더 가드 완벽 가이드 | #ifndef vs #pragma once 실전 비교
- C++ Macro Programming | “매크로 프로그래밍” 가이드
관련 글
- C++ 전처리기 |
- C++ Command Pattern 완벽 가이드 | 실행 취소와 매크로 시스템
- C++ 헤더 가드 완벽 가이드 | #ifndef vs #pragma once 실전 비교
- C++ Macro Programming |
- C++ 전처리기 완벽 가이드 | #define·#ifdef