2.11 Header guards

주홍영·2022년 3월 11일
0

Learncpp.com

목록 보기
35/199

https://www.learncpp.com/cpp-tutorial/header-guards/

우리는 function identifier는 하나의 정의만을 가질 수 있다는 것을 알고 있다
그런데 헤더 파일은 파일 내부에서도 include해서 사용하는 경우가 많다
만약 이를 취합해서 compile하면 naming collision으로 compile error가 발생한다
이러한 문제를 방지하고자 고안된 방법이 Header guard이다

Header guard

#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE

// your declarations (and certain types of definitions) here

#endif

다음과 같은 방법으로 만약 다른 헤더파일에서 지금 헤더파일이 이미 포함되어서
사용되고 있다면 not define을 하는 방식으로 사용할 수 있게된다

#pragma once

앞서 말한 헤더가드를 손쉽게 사용하는 방법이다
파일 맨 처음에 #pragma once 지시문을 선언해 준다면
헤더가드 처럼 사용할 수 있다

단, #pragma once는 c++의 공식 파트가 아니므로 다른 컴파일러에서 컴파일이 되지 않을 수도 있기에 전통적인 header guard 문법을 추천하는 바이다

Quiz

Q1 Add header guards to this header file:

int add(int x, int y);

Solution

#ifndef ADD_H
#define ADD_H

int add(int x, int y);

#endif
profile
청룡동거주민

0개의 댓글