#pragma once
헤더파일을 만들면 들어가는
#pragma once: only include once.
하나의 translation unit에 헤더가 여러 번 들어가는 것을 방지
(#: preprocessor statement)
헤더가 여러 번 include 되게 되는 상황 예시:
log.h
#include <iostream>
void shout(const char* mes){
std::cout << mes << std::endl;
}
common.h
#include log.h
int common_func(){
shout("hello");
}
main.cpp
#include log.h
#include common.h
int main(){
// main code
}
이렇게 하면 결국 main.cpp에 log.h 가 중복되어 들어감.
log.h에 #pragma once를 해주면 에러가 사라질 것, 한 번 include된 log.h를 다시 include하지 않기 때문
이런 header guard 역할을 위해 #pragma once를 쓰지만, 실제론 #ifndef를 사용.
#pragma once가 코드가 더 깔끔해 보이는데 현업에서는 #ifndef ~ #endif를 주로 사용한다고...
#ifndef
#ifndef MYLOGGER //만약 MYLOGGER이 정의되어 있지 않다면 아래를 실행한다. (#endif까지)
#define MYLOGGER
//whatever
#endif
include <> 와 include ""차이
- if the file to be included is in these folders, <> is used. <>로 include할 때는 이 파일이 include directory에 존재해야 한다.
- else if the file is relative to current file, "" is used 혹은 for everything.
ex) 만약에 내가 include하고자 하는 파일이 현재 이 파일이 존재하는 디렉터리의 상위 디렉터리에 있다면
#include "../myheader.h" 이렇게 include해줄 수 있다.
ex) iostream include할 때 그냥 #include "iostream" 해도 알아서 인클루드 디렉터리에서 찾을 수 있음
왜 iostream에는 extension이 안붙을까? > 그냥 C++를 설계한 사람이 그렇게 만든 것. C 표준 라이브러리를 불러올 땐 stdlib.h 처럼 extension이 붙음. iostream도 extension이 안붙지만 그냥 파일임.
'언어 > C&C++ 기본' 카테고리의 다른 글
[C++] Static (0) | 2021.07.01 |
---|---|
[C++] Class (0) | 2021.06.25 |
[C++] Variables, Functions, Pointers, References (0) | 2021.06.14 |
[C++] Linker (0) | 2021.06.14 |
[C++] Compiler (0) | 2021.06.14 |