5

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.

Arty
  • 14,883
  • 6
  • 36
  • 69

1 Answers1

4

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;
}
Arty
  • 14,883
  • 6
  • 36
  • 69
  • Module file definitions are not supposed to use `.hpp` and `.cpp` suffixes in Visual Studio (and likely other build systems). They use the `.ixx` and `.cppm` suffixes in VS. You're basically [avoiding all of the special things VS does to help build module files](https://devblogs.microsoft.com/cppblog/standard-c20-modules-support-with-msvc-in-visual-studio-2019-version-16-8/#include-translation). – Nicol Bolas Apr 30 '21 at 13:44
  • @NicolBolas You know why I used .hpp/.cpp? Because I'm making cross-platform/cross-compiler projects right now, I can make this note in my question for clarity. It means that I want same sources to be able to compile in CLang/GCC too and both on Win and Linux. It means there is no point to make MSVC-specific extension .ixx/.cppm. More then that I'm not makes vcxproj/sln files at all right now, I'm only considered about low-level command line invocation for compiling in MSVC, and this low-level invocation like above doesn't need any special extensions to be compilable. – Arty Apr 30 '21 at 14:01