줘이리의 인생적기

09. [C++] 전처리기(ifndef, ifdef, endif) 본문

공부/C++

09. [C++] 전처리기(ifndef, ifdef, endif)

줘이리 2021. 9. 3. 23:00
728x90

전처리기 ifndef, ifdef, endif에 대해 알아보겠습니다.

 

ifndef은 define이 되지 않았다면이라는 뜻이고

ifdef은 define이 되었다면이라는 뜻입니다

 

예제로 알아보겠습니다.

 

#include <iostream>
using namespace std;

#define NUMBER

int main() {

#ifndef NUMBER
	cout << "number not define" << endl;
#endif

#ifdef NUMBER
	cout << "number define" << endl;
#endif

	return 0;
}

#define NUMBER로 NUMBER가 define되어 있습니다.

 

그렇다면 결과는 ifdef으로 가겠죠?

잘 적용이 되었네요

 

#include <iostream>
using namespace std;

// #define NUMBER

int main() {

#ifndef NUMBER
	cout << "number not define" << endl;
#endif

#ifdef NUMBER
	cout << "number define" << endl;
#endif

	return 0;
}

define을 주석처리 한다면, ifndef으로 가겠죠?

 

잘 적용이 되었습니다

 


전처리기의 적용 범위는 어디일까요?

cpp파일을 2개 만들어서 실험해보았습니다.

 

첫 번째 main cpp파일 코드입니다.

#include <iostream>
using namespace std;

#define NUMBER

void something();

int main() {

	something();

	cout << "** main cpp file **" << endl;
#ifndef NUMBER
	cout << "number not define" << endl;
#endif

#ifdef NUMBER
	cout << "number define" << endl;
#endif
	return 0;
}

두 번째 cpp파일 입니다.

#include <iostream>
using namespace std;

void something() {
	cout << "** another cpp file **" << endl;
#ifndef NUMBER
	cout << "number not define" << endl;
#endif

#ifdef NUMBER
	cout << "number define" << endl;
#endif

}

결과가 어떻게 나올까요?

 

파일내에서만 define이 적용된다고 볼 수 있겠네요!

 

전처리기 ifndef, ifdef의 사용법에 대해서 알아보았습니다.

'공부 > C++' 카테고리의 다른 글

11. [C++] 부동소수점(float)  (0) 2021.09.24
10. [C++] 자료형 크기, 범위(sizeof, numeric_limits)  (0) 2021.09.17
08. [C++] 헤더가드  (0) 2021.09.01
07. [C++] 헤더파일(.h)  (0) 2021.08.30
06. [C++] 함수 선언, 정의  (0) 2021.08.27