0%

Experimental on C++ modules in VS2015 Update 1

又一個實驗性質的玩意,由於目前沒有IDE支持,一切從零開始。

一個簡單的範例

1
2
3
4
5
module Math;
export int add(int x, int y)
{
return x + y;
}

命名成add.ixx
接著main進來了

1
2
3
4
5
6
7
#include <stdio.h>
import Math;
int main()
{
printf("2 + 3 = %d\n", add(2, 3));
return 0;
}

以下是編譯過程

1
2
3
4
C:\> cl /c /experimental:module add.ixx
C:\> cl /experimental:module /module:reference Math.ifc main.cpp add.obj
C:\> main.exe
2 + 3 = 5

一切都看起來很美好
如果我們新增一個sub.ixx

1
2
3
4
5
module Math;
export int sub(int x, int y)
{
return x - y;
}

main也順勢改寫

1
2
3
4
5
6
int main()
{
printf("2 + 3 = %d\n", add(2, 3));
printf("3 - 2 = %d\n", sub(3, 2));
return 0;
}

這下子編譯救出錯了

1
2
3
4
5
C:\> cl /c /experimental:module add.ixx
C:\> cl /c /experimental:module sub.ixx
C:\> cl /experimental:module /module:reference Math.ifc main.cpp add.obj sub.obj
main.cpp
main.cpp(5): error C3861: 'add'

這個情況看起來Math.ifc被sub.ixx複寫了,以至於add的資訊消失。雖然可以用Module subdomain斃掉,不過這樣子很難用啊。

Template

試著在ixx當中放一些Template function,不過完全無效。還是只能放在Header file當中。

結論

有了Module之後,除了Template這種避不開的之外,Header file的重要性可能會大大降低 (再也不用擔心Winsock.h 跟 Windows.h的恩怨情仇了)。也能加速奇編譯速度。不過還在實驗階段,靜觀其變吧。