2.9 Introduction to the preprocessor

주홍영·2022년 3월 11일
0

Learncpp.com

목록 보기
33/199

https://www.learncpp.com/cpp-tutorial/introduction-to-the-preprocessor/

이번 섹션에선 preprocessor에 대해서 이야기 한다

Preprocessor directives (전처리기 지시문)

directives는 지시문으로 해석하자

includes

#include라는 지시문을 이용해 우리는 included된 파일의 내용물을 포함시킬 수 있다

defines

#define 지시문은 코드의 text를 정의된 다른 텍스트로 치환시켜준다

#define MY_NAME "Alex"

위와 같은 경우 코드의 MY_NAME이 모드 "Alex"로 그대로 치환된다

반면 substituion text가 없는 경우는 어떻게 될까?

Object-like macros without substitution text

#define USE_YEN

위와 같은 경우 USE_YEN이 생략되는 것처럼 보인다
즉, 공백으로 대체된다
위의 활용법은 상당히 쓸모가 없어 보인다
이는 나중에 다루도록 한다

Conditional compilation

여기서 compilation은 compile로 생각하면 될 것 같다
조건부 전처리 지시문이 있다
#ifdef, #ifndef, #endif

다음과 같이 활용한다

#include <iostream>

#define PRINT_JOE

int main()
{
#ifdef PRINT_JOE
    std::cout << "Joe\n"; // will be compiled since PRINT_JOE is defined
#endif

#ifdef PRINT_BOB
    std::cout << "Bob\n"; // will be ignored since PRINT_BOB is not defined
#endif

    return 0;
}

PRINT_JOE가 define 되어 있으므로
Joe가 출력된다는 것을 알 수 있다

#ifndef는 위의 반대 경우이다

#include <iostream>

int main()
{
#ifndef PRINT_BOB
    std::cout << "Bob\n";
#endif

    return 0;
}

PRINT_BOB가 #define되지 않았으므로
Bob이 출력된다는 것을 알 수 있다

if 0

#if 0의 전처리 지시문도 존재한다
이 지시문은 exclude 할 때 사용하면된다
예시는 다음과 같다

#include <iostream>

int main()
{
    std::cout << "Joe\n";

#if 0 // Don't compile anything starting here
    std::cout << "Bob\n";
    std::cout << "Steve\n";
#endif // until this point

    return 0;
}

따라서 Bob과 Steve는 출력되지 않고
오직 Joe만 출력된다

The scope of defines

#define의 유효 범위는 하나의 파일이다
따라서 main에서 define을 하고
다른 cpp 파일에서 ifdef를 사용하면 유효하지 않게 된다

단어장

compilation : 편집

profile
청룡동거주민

0개의 댓글