r/cpp_questions • u/FreakinApplePie2579 • 4d ago
OPEN i'm having trouble with MSVC modules and static initialisation
UPDATE: I managed to narrow down code. Updated post body.
AFAIK, non-local variables exported from a module should be initialised before consumer of said module runs it's code; it was done to eliminate the notorious static initialization order fiasco. However, it doesn't seem to work in my project and I wonder if it's MSVC bug or there's something I'm missing:
// paths.cppm
export module paths;
import std;
export namespace paths
{
const std::filesystem::path root_dir = []() {
return std::filesystem::path(L"readme");
}();
}
--------------------
// fileloader.cpp
export module fileloader;
import paths;
//import std; // reachable through paths?
export namespace fileloader
{
};
// this runs before paths::root_dir static initialiser!
static const bool init_files = []() {
for (const auto& entry : std::filesystem::directory_iterator(paths::root_dir)) {
;
}
return true;
}();
1
Upvotes
3
u/sephirostoy 4d ago
I don't think modules have anything to do with initialization order.
What matters is the final binaries (exe, dll) where they are stored. If a.exe depends on b.dll then the global variables from b are initialized first when b.dll is loaded, then those in a are initialized when a.exe is loaded. However, within the same binary, the order are not controllable, it depends on the linker.
2
u/CounterSilly3999 4d ago
Didn't get the question actually, just I think global/static variables are initialized not by calling some routine, rather by the loader -- fetching the values from the data segment set during compilation.
4
u/ludonarrator 4d ago
Modules and MSVC quirks apart, global variables (non-
constexpr) have always been a bad idea in C++, and it's also bad design/engineering in general.0
u/not_a_novel_account 4d ago
The other comments here are wrong. Your understanding of modules is correct. This is an MSVC bug.