How to compile/use header units in MSVC from command-line?

Viewed 277

For example I have following toy files:

mod.hpp

#include <iostream>

use.cpp

import "mod.hpp";

int main() {
    std::cout << "Hello, World!" << std::endl;
}

But if you compile it like cl use.cpp /std:c++latest then I get error

error C7612: could not find header unit for 'mod.hpp'

How do I create/use header units in MSVC?

NOTE: I'm making cross-platform/cross-compiler projects right now. It means that I want same sources to be able to compile in MSVC/CLang/GCC on both Windows and Linux. For me there is no point to make MSVC-specific extensions .ixx/.cppm, thats why I used .hpp/.cpp in my case. More then that I'm not making .vcxproj/.sln files at all, I'm only considered about low-level command line invocation for compiling in MSVC.

This question was made by me just to share my answer with ready-made solution.

1 Answers

To create precompiled header unit issue next command:

cl /EHsc /std:c++latest /exportHeader mod.hpp

this command creates mod.hpp.ifc file, which is a precompiled header unit module. Here is documentation about /exportHeader flag.

Then to use header unit issue command:

cl /EHsc /std:c++latest use.cpp /headerUnit mod.hpp=mod.hpp.ifc

documentation about /headerUnit is here. /headerUnit accepts param header-filename=ifc-filename. After command above final program compiles and outputs:

Hello, World!

This way you can precompile any header, including standard ones like import <iostream>;.

For commands above I used following files:

mod.hpp

#include <iostream>

use.cpp

import "mod.hpp";

int main() {
    std::cout << "Hello, World!" << std::endl;
}
Related