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.
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.
Your code is correct and it correctly compiles with gcc-15:
// modultest.cppm
module;
#include <iostream>
export module modultest;
export class Test {
public:
Test() {}
void print() { std::cout << "hi" << std::endl; }
};
// main2.cpp
import modultest;
import std; // also supported in gcc-15 with c++23
int main() {
Test t;
t.print();
return 0;
}
Building it, generates gcm.cache/modultest.gcm (around 6.2MB):
g++-15 -std=c++20 -O3 -fmodules modultest.cppm main2.cpp
Including import std; from C++23 is also supported on gcc-15 (this also generates gcm.cache/std.gcm, with around 30MB):
g++-15 -std=c++23 -O3 -fmodules modultest.cppm main2.cpp -fsearch-include-path bits/std.cc
# running it on bash
$ ./a.out
hi
CMake 4.0 also supports building this with GCC 15 or Clang 19 (see CMakeLists.txt below):
cmake_minimum_required(VERSION 4.0.0)
set(CMAKE_CXX_COMPILER /usr/bin/g++-15)
# set(CMAKE_CXX_COMPILER /usr/bin/clang++-19)
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "a9e1cf81-9932-4810-974b-6eccaf14e457")
set(CMAKE_CXX_MODULE_STD 1)
project(example2 VERSION 0.1.0 LANGUAGES CXX)
add_library(modultest)
target_sources(modultest PUBLIC FILE_SET CXX_MODULES FILES modultest.cppm)
add_executable(example2 main2.cpp)
target_link_libraries(example2 PRIVATE modultest)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With