Its Me
Its Me

Reputation: 156

Unable to Import C++ Modules

I'm trying to rebuild a project of mine in C++ 20 using modules to reduce dependencies and compilation times. I tried importing some modules, and I'm able to do so, yet Visual Studio marks the importation statements as undefined: "Could not find module file for...". Although it marks it as wrong, I'm still able to compile and run the imported functions (although it doesn't allow me to compile a function if it requires a separate #include found only in the module but not the .cpp file it imports to, giving me a linker error). I followed Microsoft's documentation closely and was able to utilize modules on an earlier project and never met any of these problems then, and I made sure to reestablish the same configurations in this project yet this happens.

I'm not really sure what other information I could provide, but please ask if any is necessary. Any help would be appreciated

Config: Config

Works

import Object;

#include <iostream>

int main() {
    calc(1, 5);
}
export module Object;

export int calc(int a, int b) {
    return a + b;
}

Doesn't Work

import Object;

#include <iostream>

int main() {
    calc(1, 5);
}
export module Object;

#include <iostream>

export int calc(int a, int b) {
    return a + b;
}

As you can see, there is multiple linking error: With include

Either way, VS marks it as an error

Edit By putting the #include above the module export statement the code compiles, but VS still marks it as an error. Although importing headers such as <iostream> or exporting classes doesn't work. So I'm able to compile, but only certain things, and VS always marks it as wrong

Upvotes: 6

Views: 11300

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41750

You cannot include like that in a module. Including a header file into a module will make all of its content part of your module. Since you do not define the implementation for the standard library function you declare from the include, it results in linking errors.

You have two choices for headers.

The first is to use global module fragments:

module;
#include <iostream>
export module Object;

// ...

The second choices is to use header units:

export module Object;

import <iostream>

Upvotes: 5

Related Questions