Coding/Tip !!
Header Gurad
IMyoungho
2018. 10. 2. 11:30
Header Guard 란??
헤더 가드의 이해를 돕기위해 예시로 설명하겠다.
예를 들어 우리가 헤더파일을 생성했을 때 main 함수와 헤더파일 내부에 아래와 같은 함수가 있다고 가정해보자.
main.cpp
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> #include "test1.h" #include "example123.h" using namespace std; int main() { cout << "hello world" << endl; example_boy(); return 0; } | ex |
test1.h
1 2 3 | int test_boy(int a, int b){ return a + b; } |
example123.h
1 2 3 4 5 | #include "test.h" void example_boy(){ test_man(1,2); } |
위의 코드들을 main.cpp에서 한번에 풀이해보면 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> //#include "test.h" -> 해더파일의 코드를 그대로 가져옴 //#include "example123.h" -> 헤더파일의 코드를 그대로 가져옴 using namespace std; int test_boy(int a, int b) -> 두번이나 중복됨 { return a + b; } void example_boy() { test_boy(1,2); } int test_boy(int a, int b) -> 두번이나 중복됨 (example123.h에서 include되었음으로 두번 불리게 된 것임) { return a + b; } int main() { cout << "hello world" << endl; example_boy(); return 0; } |
이런식의 코드에서 발생할 수 있는 문제점은 보다시피 include가 여러번 진행되어 에러가 발생하게 된다는 점이다.
이러한 현상이 발생하게 되면 함수 재정의에 대한 에러가 발생하게된다.
-> 이를 막기위해 사용하는 것이 바로 헤더 가드이다!
헤더파일의 아래 윗 부분에
1 2 3 4 5 6 | #ifndef TEST_H(헤더파일이름이다.) #define TEST_H ....(작성코드) #endif |
해주거나
1 | #pragma once |
를 해주게 되면 중복되는 경우 한번만 include만 진행하라는 의미가 되어서 에러가 발생하지 않는다.
위의 #ifdef 와 #endif는 다른 식으로도 사용이 가능하다
1 2 3 4 5 6 | #define HELLO int main(){ #ifdef HELLO cout << " My name is Hello " << endl; #endif } |
이런식으로 define으로 매크로를 걸었을 때 위의 매크로에 대해 정의 할 수 있다.
만약 define을 하지 않았다면 #ifndef와 #endif를 사용해주면 된다.
1 2 3 4 5 6 7 8 9 10 | //#define HELLO int main(){ #ifdef HELLO cout << " My name is Hello " << endl; #endif #ifndef HELLO cout << "위와 똑같은 것 같지만 자세히보면 이건 if not define 이다" << endl; #endif } |
반응형