C++복습

C++복습) C++20/Module

PJNull 2022. 2. 4.
728x90
반응형

Module은 C++20에서 가장 중요한 함수라고 해도 과언이 아니다. 당장 상용엔진에서의 활용은 다소 어려울지 모르나, 향후 3~4년이내에 서버쪽에서는 높은 활용도를 가지지 않을까 생각한다. 

 

 

Module의 필요성

 

Moudule은 C++의 고질적인 문제인 컴파일 시간을 단축시켜준다는 장점이 있다.

기존 빌드단계는 전처리(#include/#define)->컴파일(오브젝트파일 생성)->링크(오브젝트들의 연관관계를 분석/연결)이다.

 

 

기존 빌드단계의 문제점

 

  • 빌드속도가 매우 느리다.

개별적으로 빌드되어 개별의 Obj파일을 만들어진다. 코드중복및 반복된 치환에 의해 또한 일어날수 있기 때문에 빌드속도가 느리다.

 

  • 매크로 문제

 

  • 심볼 중복 정의

동일한 이름의 심볼/함수가 존재할 경우 링크 단계에서 충돌하는 경우가 있다.

 

 

Module의 필요성

 

  • Module은 딱 한번만 import됨

 

  • import순서에 상관이 없음.

 

  • 심볼 중복정의 문제가 해결됨

 

  • 모듈의 이름 지정 가능

 

  • 인터페이스/구현부 분리 관리할 필요없음

 

 

Module의 종류

 

 함수앞 export형

//Test.ixx
export module Test;

export int Add(int a,int b)
{
	return a + b;
}
//C++.cpp

import Test;

int main()
{
  int sum=Add(1,2); //sum=3
}

 

 export묶음

//Test.ixx
export module Test;

export
{
	int TestEx(int a,int b)
	{
		return a + b;
	}
	int TestEx2(int a, int b)
	{
		return a * b;
	}
}
//C++.cpp

import Test;

int main()
{
  int sum=TestEx(1,2);//sum=3
  int mul=TestEx2(2,3);//mul=6
}

 

 namespace 지정

//Test.ixx
export namespace Test
{
	int  TestEx(int a, int b)
	{
		return a + b;
	}
}
//C++.cpp

import Test;

int main()
{
  int sum=Test::TestEx(1,2);//sum=3

}

 

 sub module

//Test_Sum.ixx

export module Test.Sum;

export int TestSum(int a, int b)
{
 return a+b;
}

 

 Partition

 

Partition은 sub module과 유사하지만 sub module과의 차이점은 소속된 Partition들은 독립적으로 사용이 불가하다.

//TestPartition.ixx

export module TestPartition;

export import :TestPartition_1;
export import :TestPartition_2;
//TestPartition_1.ixx

export module TestPartition:TestPartition_1;
//TestPartition_2.ixx

export module TestPartition:TestPartition_2;
//C++.cpp


import TestPartition;
import TestPartition_1;//Error

int main()
{
}

 

module의 외부 참조

module또한 외부라이브러리에서 참조를 해야될 경우가 생길수 있다.

이럴경우 최상단에 global module fragment를 붙이고 참조할 것들을 붙이는 방식으로 이용할수 있다.

//Test.ixx

module;//   global module fragment

//참조영역
#include "iostream"
#include <vector>


//Module 시작
export namespace TestEx()
{
}

//import Module

export import Test.Sum;// sub module import

 

728x90
반응형

'C++복습' 카테고리의 다른 글

C++복습) vector(반복자)  (0) 2022.03.11
C++복습) vector(동작원리)  (0) 2022.03.09
C++복습) C++20/Concept  (0) 2022.01.10
C++복습) Modern C++/smart pointer  (0) 2022.01.03
C++복습) Modern C++/lambda  (0) 2021.12.30

댓글