고흐의 연구실/C언어와 C++
[C언어] 조건부 컴파일 #ifdef #endif #if #ifndef
전고흐
2020. 10. 11. 22:47
728x90
#ifdef에 매크로를 지정하면 해당 매크로가 정의되어 있을 때만 코드를 컴파일합니다.
#ifdef 매크로
코드
#endif
example)
#include <stdio.h>
#define DEBUG // DEBUG 매크로 정의
int main()
{
#ifdef DEBUG // DEBUG 매크로가 정의되어 있다면 #ifdef, #endif 사이의 코드를 컴파일
printf("Debug: %s %s %s %d\n", __DATE__, __TIME__, __FILE__, __LINE__);
#endif
return 0;
}
>> 결과 : Debug: Oct 6 2015 23:30:18 c:\project\hello\conditional_compile\conditional_compile.c 8
#if로 값 또는 식을 판별하여 조건부 컴파일
#if 값 또는 식
코드
#endif
example)
#include <stdio.h>
#define DEBUG_LEVEL 2 // 2를 DEBUG_LEVEL로 정의
int main()
{
#if DEBUG_LEVEL >= 2 // DEBUG_LEVEL이 2보다 크거나 같으면 #if, #endif 사이의 코드를 컴파일
printf("Debug Level 2\n");
#endif
#if 1 // 조건이 항상 참이므로 #if, #endif 사이의 코드를 컴파일
printf("1\n");
#endif
#if 0 // 조건이 항상 거짓이므로 #if, #endif 사이의 코드를 컴파일하지 않음
printf("0\n");
#endif
return 0;
}
>> 결과 : Debug Level 2
1
#if와 defined의 조합
#if defined 매크로
코드
#endif
example)
#include <stdio.h>
#define DEBUG // DEBUG 매크로 정의
#define TEST // TEST 매크로 정의
int main()
{
// DEBUG 또는 TEST가 정의되어 있으면서 VERSION_10이 정의되어 있지 않을 때
#if (defined DEBUG || defined TEST) && !defined (VERSION_10)
printf("Debug\n");
#endif
return 0;
}
>> 결과 : Debug
#elif와 #else를 사용
#ifdef 매크로
코드
#elif defined 매크로
코드
#else
코드
#endif
#if 조건식
코드
#elif 조건식
코드
#else 코드
#endif
example)
#include <stdio.h>
#define USB // USB 매크로 정의
int main()
{
#ifdef PS2 // PS2가 정의되어 있을 때 코드를 컴파일
printf("PS2\n");
#elif defined USB // PS2가 정의되어 있지 않고, USB가 정의되어 있을 때 코드를 컴파일
printf("USB\n");
#else // PS2와 USB가 정의되어 있지 않을 때 코드를 컴파일
printf("지원하지 않는 장치입니다.\n");
#endif
return 0;
}
>> 결과 : USB
#ifndef는 매크로가 정의되어 있지 않을 때 코드를 컴파일
#ifndef 매크로
코드
#endif
example)
#include <stdio.h>
#define NDEBUG // NDEBUG 매크로 정의
int main()
{
#ifndef DEBUG // DEBUG가 정의되어 있지 않을 때 코드를 컴파일
printf("main function\n");
#endif
return 0;
}
>> 결과 : main function
*추가 : NDEBUG는 "not debug"
728x90