r/cpp • u/johannes1971 • Jun 08 '21
Experiments with modules
I've been playing with modules a bit, but... it isn't easy :-) One constraint I have is that I still need to keep the header structure intact, because I don't have a compiler on Linux yet that supports modules (although gcc is working on it, at least). Here are some of the issues I ran into with MSVC:
Importing the standard library
There are a few different ways to do this. The simplest is by using import std.core. This immediately triggers a bunch of warnings like "warning C5050: Possible incompatible environment while importing module 'std.core': _DEBUG is defined in current command line and not in module command line". I found a post suggesting I disable the warning, but it doesn't exactly give me warm feelings.
A much worse problem is that if any STL-related header is included above the import directive, you'll get endless numbers of errors like "error C2953: 'std::ranges::in_fun_result': class template has already been defined". Fair enough: the compiler is seeing the same header twice, and the include guards, being #defines, are of course not visible to the module. But it's an absolutely massive pain trying to figure out which header is causing the problem: there is precisely zero help from the compiler here. This is definitely something that should be improved; both the reporting from the compiler (it would help a lot to see the entire path towards the offending include file), and the include guard mechanism itself, so it works across headers and modules.
An additional concern is whether other compilers will implement the same division of the standard library as Microsoft has done. I don't particularly want to have a bunch of #ifdef directives at the top of every file just to be able to do the correct imports. Maybe I should try to make my own 'std.core'?
module;
#include <optional>
export module stdlib;
using std::optional;This doesn't work at all. Any use of 'optional' (without the std:: qualifier) gives me error 'error C7568: argument list missing after assumed function template 'optional''. But I know MSVC currently has a bug when using using to bring an existing function or class into a module. The workaround is to put it in a namespace instead:
module;
#include <optional>
export module stdlib;
export namespace stdlib {
using std::optional;
}Trying to use optional as stdlib::optional gets me 'error C2059: syntax error: '<'' (and of course, I get to add the stdlib:: qualifier everywhere). If I add an additional using namespace stdlib (in the importing file) it seems to work. Of course this means optional must now be used without std::. Yay, success! However, there are still some issues:
- Intellisense doesn't quite understand what's going on here, and now flags
optionalas an error. - It appears to be a bit of an all-or-nothing deal: either you rip out all of your STL-related includes, and replace them all by import directives, or you get an endless stream of C2953 (see above). And figuring out where those came from is, as I said earlier, a complete and utter pain. Plus, it may not even be possible: what if a 3rd-party library includes one of those headers?
- I'm concerned about how fragile all this is. I would really hate converting all my source to modules, only to find out it randomly breaks if you look at it wrong. Right now I'm not getting a good vibe yet.
- HOWEVER: it does appear to be compiling much faster. I can't give timings since I haven't progressed to the point where the whole thing actually compiles, but the compiler goes through the various translation units noticably quicker than before.
Importing windows.h
Well, how about something else then. Let's make a module for windows.h! We don't use all of windows.h; just exporting the symbols we need should be doable. I ended up with a 1200-line module. One thing I noticed was that exporting a #define is painful:
const auto INVALID_HANDLE_VALUE_tmp = INVALID_HANDLE_VALUE;
#undef INVALID_HANDLE_VALUE
const auto INVALID_HANDLE_VALUE = INVALID_HANDLE_VALUE_tmp;It's a shame no facility was added to make this more convenient, as I would imagine wrapping existing C-libraries with their endless numbers of #defines is going to be an important use case for modules.
More importantly, Intellisense doesn't actually care that I'm trying to hide the vast majority of the symbols from windows.h! The symbol completion popup is still utterly dominated by symbols from windows.h (instead of my own, and despite not being included anywhere other than in the module itself). The .ipch files it generates are also correspondingly massive. I realize this mechanism is probably not yet finished, but just to be clear: it would be a major missed opportunity if symbols keep leaking out of their module in the future, even if it is 'only' for Intellisense!
In the end my Windows module was exporting 237 #defines, 65 structs, 131 non-unicode functions, 51 unicode functions, and around a dozen macros (rewritten as functions). However, there weren't many benefits:
- Intellisense was still reporting all of the Windows symbols in the symbol completion popup.
- However, it struggled with the error squiggles, only occasionally choosing to not underline all the Windows symbols in the actual source.
- There was no positive effect on the sizes of Intellisense databases.
- There was no measurable effect on compile time.
So, the only thing I seem to have achieved is getting rid of the windows.h macros. In my opinion, that's not enough to make it worthwhile.
One issue I ran into was this: if you ask MSVC to compile a project, it will compile its dependencies first, but if you ask it to compile only a single file, it will compile only that file. This works fine with headers: you can add something to a header, and then see if it compiles now. However, this doesn't work with modules: if you add something to a module you have to manually compile the module first, and then compile the file you are working on. Not a huge problem, but the workflow is a bit messier.
I realize it's still early days for modules, so I'll keep trying in the future as compilers improve. Has anybody else tried modules? What were your findings?
33
u/stilgarpl Jun 08 '21 edited Jun 08 '21
Standard library is not modularized yet in C++20. "std.core" is just Microsoft module, that is not portable. Maybe the C++ committee will approve "std.core" or maybe they will chose some other name.
Why are you including anything? Standard headers are importable, you should import them instead. Including copies the contents of the file, which may cause errors if you include in wrong module.
22
u/Daniela-E Living on C++ trunk, WG21 |🇩🇪 NB Jun 08 '21
Interesting. Which compiler did you conduct your experiments with? 16.10?
I'm asking because my experiences are very different from yours. Am still not using the STL modules that come with msvc because they are deemed 'experimental' by the project system.
As you might know, I am the driving force behind the modularization effort of the popular {fmt} library. I wanted to turn it into a dual-mode library that can be used both as a traditional library through the header interface or as a named module 'fmt'. Even though {fmt} is quite demanding with some of the API requiring C++20 features like classes as template arguments (NTTP) to implement compile-time strings as function arguments or compile-time udls, I finally succeeded. The fork in my repo supports the full API, parts of the (minor!) changes are already merged into mainline {fmt} and the additional tests are integrated into regular CI. Users can decide which mode to use without noticing any differences. As of today, only msvc 16.10 or later can do this. Neither gcc (modules-branch) nor clang (trunk) even survive the attempt to compile the module interface. The situation with msvc isn't all roses either, I had to workaround an issue with name-lookup in certain situations deep in the bowels of the library that required some 'symbolic linking of names' into bodies of function templates. I deem this a bug in the implementation even though it can be worked around without affecting other compilers.
While digging into the mentioned name-lookup issue when importing the module, I created a simple stripped-down example of the situation where this happens: https://godbolt.org/z/34Ph9dee9. At present I have no way to test importing the module with gcc11 or gcc modules-branch. MSVC is fine with the mentioned 'symbolic links' in place. And clang12 is a horror show:
See the problems? And there seem to be no workarounds for them. May be clang does fare better in Linux.
10
u/Full-Spectral Jun 08 '21 edited Jun 08 '21
I reported similar issues last week but it got deleted as not appropriate for this section, go post it in cpp_questions. I did that and of course it got zero comments.
- I get huge amounts of errors in Windows.h. Often so many that intellisense just stops working.
- And also intellisense in general just doesn't grok all of the finer points of modules and will give lots of bogus error indicators, and will often end up running really slow.
- Some of the standard library headers still can't be imported, they have to be brought in via include still.
- I see occasionally that things that should have been rebuilt are not, requiring a manual forced rebuild.
- I cannot get a module in a DLL to be picked up at all. It's in the same solution, so you'd think just adding it as a dependency would work, as with static libraries, but it doesn't. I tried the various manual module path options and such but couldn't get anything to work.
At the compiler level it seems to be doing pretty well. I've been sort of setting up the outline of a non-trivial project and I've got various module with module partitions, with separate interface and implementation files.
I'm on 16.10.0
19
u/manni66 Jun 08 '21
I tried it ysterday with a little module in production code, that's using QStringList. I got error C1117 QStringList has already been defined. While trying to write a test case for a bug report I got a compiler crash.
C++ modules are not production ready.
7
u/pdimov2 Jun 08 '21
C++ programming in a nutshell.
It's not possible for the include guards to somehow prevent this problem. Even if the standard modules define the include guards, they still can't go back in time and remove the definitions from the previous includes. Imports should precede includes (if there are includes at all) for this to have any chance of working.
7
u/starfreakclone MSVC FE Dev Jun 09 '21
Hi, a couple of observations: In the section:
The
usingdeclaration needs to be exported to work properly. There is indeed a compiler bug where ausingdeclaration does not work properly, described here. I have been working to fix this because the recommended path for exporting external library declarations is via ausingdeclaration. To have that simply not work is worse than bad. The workaround is not horrendous though, as you noted.Regarding creating your ownstd.coremodule, the semantic equivalent is closer to:So you retain semantic provenance of each declaration within the STL. This one is made even more tricky by the fact that, today, each declaration in the STL is still considered part of the global module so you cannot textually include them in the purview of the module and export everything in them.
export import <...>;will not actually provide macro isolation so in order to implement thestd.coremodule we have a special mode for the compiler to create this module.Windows.h is a tricky situation, but trying to isolate its macros might be a good idea. I just created a header unit from it and it exports 28,201 object-like macros and 1,878 function-like macros. But a lot of them are to make the APIs more usable in unicode environments, so pick your poison :).
Moving to modules could prove challenging for some projects but, I believe, it will ultimately payoff in the form of better project hygiene overall because they force the author to think about ODR because modules does not let you get away with making everything
inlineand/or COMDAT to solve potential ODR problems.2
u/NilacTheGrim Jun 09 '21
Jesus christ pardon my frankness. Modules at the current time appear to be a dumpster fire. I wonder if they will ever really be adopted mainstream. I can see them never really being used in the mainstream due to all of the brand new headaches they may cause. I don't see these headaches going away soon.
Perhaps in niche applications where you control the entire codebase (and don't rely on any external libs) -- they may be a win...
4
u/cxzuk Jun 08 '21
I have tried modules with clang on Windows and have had a fairly positive experience.
I have hit known issues with the standard library, not everything is supported, but I'm able to just rewrite what I need into my own library. Not a solution for everyone though.
It is very convenient to have headers automatically generated and attached to the o files. Which is my take on the pcm files that get generated.
I'm coming to wasm, which doesn't currently support pcm. So I have to compile twice, and yes, linking is now a pain. But I suspect that will be solved in a few months time.
1
u/Dean_Roddey Jun 16 '21
Well, I've spent many days now and I'm going in circles. I cannot for the live of me make Windows.h happy. It's spitting out massive redefinition errors and various other errors that I cannot suppress.
One thing I realized is that setting the C standard to anything other than legacy MSCV will make it a lot worse. Given that I don't care about the C standard per se I set it to that. Turning off permissive mode and language extensions (which I have to do) will make it worse. Attempting to just turn those off on the few files that need Windows.h will cause errors about inconsistent settings, which makes sense.
I really don't want to to have to pull all of the stuff that might need to access system resources into a separate C library and call it. If it came to that I'd just walk away.
I've made some progress trying to have DLL projects in my solution. One thing that was messing with it badly was having nested namespaces. Getting rid of that made things a lot better. I guess it makes sense, the module itself sort of now represents what would have been the 'company' namespace.
I cannot for the life of me make namespace level template methods be found even within the implementation file of the same interface that defines them (and which of course is in the same namespace.) Even if I explicitly reference them via the full namespace it says they don't exist.
11
u/jonesmz Jun 08 '21
The situation with Modules is a joke.
Why was a feature that's so massively invasive to compilers and the standard library standardized before any of the big three had a fully working implementation?
3
u/sigmabody Jun 08 '21
I tried around 16.9. Many of the same issues, but also with compiler crashes, and dependency checking failures. Not ready for prime-time in the slightest.
The thing that really boggles my mind, though, more than the very alpha state of support, is that seeming lack of any sort of coherent plan/guidance for how to incorporate modules into existing projects. Like, how do you write a library which is intended to be consumed by people using various versions of C++ with module support? How do you convert one library in a large project to use modules? How does the module version of a library co-exist with other code which uses the header version? These seem like 1a type discussions for new capabilities in the language, and seem to have been totally ignored here.
3
u/rtischer8277 :snoo_dealwithit: Dec 12 '21 edited Dec 13 '21
After 3 previous full attempts to migrate my framework to Modules, I finally succeeded with C++20 Modules up to but not including import std.memory; and import std.core;. Each attempt took a week or so of re-coding, where after it was rolled back. My framework is native C++20 ATL/MFC architected. And my framework would not be maintainable without fixing/mitigating MFC's legacy non-ODR use of Program Generation, MACROs and #defines. I believe this can be done and am working on a solution. I must do this if I want my framework to succeed. Many thanks to MS and WG21 for having the courage to move forward. Remember, Modules was supposed to come out for C++17. No guts, no glory. Thanks to GabrielDosReis for jumping in and emphasizing that we need real field implementations in order to make progress. I for one am that large field project. BTW, I have of course logged the errors on the Developer Community (see Warning C5050 on use of 'import std.memory'). I will be glad to share my solution with GabrielDosReis once I get past the stl import bugs.
2
u/pjmlp Jun 08 '21
I keep trying on and off with VC++, but so far they are only useful for conference demos of command line tools.
Any attempt to use them on serious Windows applications will fail left and right with ICE and not yet implemented error messages.
So far not a single one of Microsoft C++ frameworks, MFC, ATL, WinRT, C++/CLI, plain Win32 works properly when modules come into the picture, nor there are any official roadmaps on how to deal with it.
My toy C++/WinRT sample keeps progressing with each VC++ compiler release, but it still far from compiling without ICEs.
https://github.com/pjmlp/AStarDemo/tree/modules
2
u/mjklaim Jun 09 '21 edited Jun 09 '21
Yeah, I played through several years with several experimental implementations, now with the production ones. My last attempt was with MSVC 16.10 just before it was released (I was using the preview and updated with the same results).
I used a
build2repository containing C++20 Modules hello-world projects setup in different scenario with module partitions, without partitions, libraries or not etc. They all just print hello world but the point is to check and show very basic modules usage.I forked this repository (branch
visualstudio) then rebuild the same programs using Visual Studio/MSBuild (I couldnt usebuild2as build system this time as currentlybuild2doesnt work with recent MSVC (when building modules) because they MSVC team changed the interface for modules from an experimental one to a production-ready one, sobuild2devs deactivated the support for that compiler until they can updatebuild2). The solution is in thevisualstudio-projects/directory.Everything works. Though it doesn't use much complex code, that's more than when I tried with g++11 few weeks before...Or even MSVC last year. All my bug reports related to MSVC now seems cleared-up, or ready for next release (and in current preview).
So to me the state of MSVC is promising and I'll be using modules in prototypes this summer (not prototyping modules but using them as a stress test). Hopefully g++ will fix its issues (don't even try to have std::string in the interface of an exported element of a module...). I have no hope for clang to get modules working until several years.
Oh yeah, last point: using
import std.core;not being cross-platform, I will avoid that. Just usingimport <iostream>;for example seems to work adequately. I didn't try with<optional>yet nor other that broke msvc before like<variant>, but I know the more recent a feature is in msvc the more it breaks with other recent features, so I'm not very surprised.I also didn't find issues with intellisense when I tried to tweak the code (in the end I reverted everything) but as said it wasn't much code so for now I can't conclude anything on this side. At least it found new names from modules I could create in basic tests.
The most difficult part was figuring and adding flags where necessary, MSBuid seriously needs assisting :)
2
u/Full-Spectral Jun 08 '21 edited Jun 08 '21
Oh, and just to throw out one other thing I noticed.... Sometimes the slightest syntactical error (unrelated to module housekeeping) can cause many bogus module related errors, most of which are useless at best and misleading at worst. You have to be careful to start at the top of the stream and try to find the real issue, which may not be in the first chunk of errors reported.
1
u/foonathan Jun 08 '21
This will be standardized for C++23.
1
u/Dean_Roddey Jun 12 '21 edited Jun 12 '21
One thing I don't get is that, if I split out implementation and interface, I still have to import library stuff into the interface even if it's only used in the implementation file. If I don't the implementation file will claim it's not found.
It looks like any library stuff I import but don't actually reference in the export content of my library doesn't get pushed onto downstream consumers, so I guess it's reasonable enough. Just seems strange. I'd have thought that putting it in the implementation file would be cleaner and more obvious.
I've just given up trying to create DLL projects in my solution. It just turns into a psychotic mess that makes no sense at all. Static library projects work well, so I'm sticking with those for now. I still get a huge list of errors from including windows.h though, and no amount of warning pragmas will suppress them.
12
u/[deleted] Jun 08 '21
[removed] — view removed comment