C 매크로 조건부 컴파일 - sonkoni/Koni-Wiki GitHub Wiki
매크로 조건문이다. #ifdef, #ifndef, #if, defined, #elif, #else, enif 를 조합해서 사용한다.
// 매크로가 정의되어 있을 때 컴파일 // DEBUG 매크로가 정의되어 있을 때 컴파일
#ifdef 매크로 #ifdef DEBUG
코드 printf("Debug\n");
#endif #endif
// 매크로가 정의되어 있지 않을 때 컴파일 // DEBUG 매크로가 정의되어 있지 않을 때 컴파일
#ifndef 매크로 #ifndef DEBUG
코드 printf("Hello, world!\n");
#endif #endif
// 값 또는 식이 참일 때 컴파일 // DEBUG_LEVEL이 2 이상일 때 컴파일
#if 값 또는 식 #if DEBUG_LEVEL >= 2
코드 printf("Debug Level 2\n");
#endif #endif
// 조건이 항상 거짓이므로 컴파일 하지 않음
#if 0
printf("0\n");
#endif
// 조건이 항상 참이므로 컴파일함
#if 1
printf("1\n");
#endif
각종 논리연산자도 사용 가능하다.
// 매크로가 정의되어 있을 때 컴파일.
// !, &&, ||로 논리 연산 가능 // DEBUG 또는 TEST가 정의되어 있을 때 컴파일
#if defined 매크로 #if defined DEBUG || defined TEST
코드 printf("Debug\n");
#endif #endif
// DEBUG가 정의되어 있으면서
// VERSION_10이 정의되어 있지 않을 때 컴파일
#if defined (DEBUG) && !defined (VERSION_10)
printf("Debug\n");
#endif
// if, elif, else로 조건부 컴파일 // DEBUG_LEVEL의 값에 따라 컴파일
#if 조건식 #if DEBUG_LEVEL == 1
코드 printf("Debug Level 1\n");
#elif 조건식 #elif DEBUG_LEVEL == 2
코드 printf("Debug Level 2\n");
#else #else
코드 printf("Hello, world!\n");
#endif #endif
// if, elif, else로 조건부 컴파일 // PS2, USB 정의 여부에 따라 컴파일
#ifdef 매크로 #ifdef PS2
코드 printf("PS2\n");
#elif defined 매크로 #elif defined USB
코드 printf("USB\n");
#else #else
코드 printf("지원하지 않는 장치입니다.\n");
#endif #endif
#include <stdio.h>
#ifndef DEBUG
#define DEBUG
#endif /* DEBUG */
int main(int argc, char *argv[]) {
#ifdef DEBUG
printf("DEBUG: %s, %s, %s, %d", __DATE__, __TIME__, __FILE__, __LINE__);
#endif
return 0;
}
// DEBUG: Jun 17 2022, 01:48:05, Untitled.c, 7-
__DATE__: 컴파일 한 날짜(실행시점이 아니라 컴파일 한 날짜가 박힘) -
__TIME__: 컴파일 한 시간(실행시점이 아니라 컴파일 한 시간이 박힘) -
__FILE__: 이 코드가 있는 해당 소스파일 -
__TIME__: 이 코드가 있는 해당 소스파일의 줄번호
#include <stdio.h>
#define DEBUG_LEVEL 2
int main(int argc, char *argv[]) {
#if DEBUG_LEVEL >= 2
printf("DEBUG: %s, %s, %s, %d", __DATE__, __TIME__, __FILE__, __LINE__);
#endif
return 0;
}
// DEBUG: Jun 17 2022, 01:48:05, Untitled.c, 7 defined (매크로) 괄호 생략 가능
#include <stdio.h>
#define DEBUG_LEVEL 0
#define TEST
#define VERSION_10
int main(int argc, char *argv[]) {
#if (DEBUG_LEVEL >= 2 || defined TEST) && !defined (VERSION_9)
printf("DEBUG: %s, %s, %s, %d", __DATE__, __TIME__, __FILE__, __LINE__);
#endif
return 0;
}
// DEBUG: Jun 17 2022, 01:48:05, Untitled.c, 7#include <stdio.h>
#define USB
int main(int argc, char *argv[]) {
#ifdef USB
printf("USB\n");
#elif PS2
printf("USB\n");
#else
printf("NO\n");
#endif
return 0;
}
// USB