[C++] module
Updated:
개요
- 기능의 일부만을 포함시킬 수 있는 기능
- 컴파일 시간 대폭 감소
#include
이용 시 소스 파일마다 헤더 파일 내용 전체를 포함module
이용 시 일부만 포함 가능되며 한번만 포함- export 하지 않는 이름은 변경하더라도 컴파일 시 import 소스파일에 영향(재컴파일)을 주지 않음
- 매크로 격리
- 서로 다른 헤더 파일에서 동일한 이름으로 define 시 include 순서에 따라 값이 달라짐
- module은 매크로 격리를 통해 순서에 따라 값이 달라지지 않음
- header guard(#ifndef, #define, #pragma once) 불필요
- global module fragment
- import가 불가능한, 즉 #include와 같은 전처리 지시자가 필요한 경우에 사용
- Global module fragment는 export되지 않음
- 해당 모듈을 사용하는 곳에서 Global module fragment의 내용을 볼 수 없음
- 문법
module; preprocessing-directives(optional) module-declaration
module;
은 처음에 선언되어야 함
예제
- math.cpp
module; #include <vector> export module math; using namespace std; auto add(const int &i1, const int &i2) { return i1 + i2; } namespace math { auto add(const int &i1, const int &i2) { return i1 + i2; } export vector<int> add(const vector<int> &v1, const vector<int> &v2) { vector<int> result((v1.size() < v2.size() ? v1.size() : v2.size())); for (unsigned int i = 0; i < result.capacity(); ++i) { result[i] = add(v1.at(i), v2.at(i)); } return result; } } // namespace math
- main.cpp
#include <iostream> #include <vector> using namespace std; import math; int main() { for (const auto &iter : math::add(vector<int>{1, 2, 3}, vector<int>{1, 2, 3})) { cout << iter << endl; } // error // cout << add(1, 2) << endl; return 0; }
- 실행 결과
2 4 6