How do i use #include with exporting modules?

426 Views Asked by At
module;
#include <iostream>
export module modultest;
export class Test{
    public:
    Test(){}
    void print(){
        
    }
};

I want to create a print function using cout, which I need <iostream> for, but if I include iostream I get multiple errors, for example:

error: redefinition of 'void operator delete(void*, void*)'
  180 | inline void operator delete  (void*, void*) _GLIBCXX_USE_NOEXCEPT { }

I'm using g++ compiler in VSCode.

2

There are 2 best solutions below

1
On BEST ANSWER

Per cppreference.com:

Importing modules and header units

...

#include should not be used in a module unit (outside the global module fragment), because all included declarations and definitions would be considered part of the module. Instead, headers can also be imported as header units with an import declaration:

export(optional) import header-name attr(optional);

A header unit is a separate translation unit synthesized from a header. Importing a header unit will make accessible all its definitions and declarations. Preprocessor macros are also accessible (because import declarations are recognized by the preprocessor).

...

So, try replacing #include <iostream> with import <iostream>; instead.

0
On

Actually, your code is correct. Includes need to be put in the global module fragment:

module; // global module fragment
#include <iostream> // correct, inside the global module fragment

export module modultest; // named module declaration

// module purview, owned by module modultest
export class Test {
    public:
    Test(){}
    void print(){
        
    }
};

This code is correct since everything after module; lives in the global module fragment, which is okay to include anything there. You then declare the named module, and anything else after that is part of the module itself.

The error you encounter is a compiler bug. This is because GCC has very poor support for module at the moment. Expect your code to work with other compiler or future version of GCC.