Search code examples
c++exceptiongccc++-modules

Do custom C++ exceptions from a module work in GCC (14.2.0)?


Are C++ modules implemented in GCC such that I can create a custom exception in a module for use in another file? I get the following error with GCC 14.2.0 via MinGW/MSYS:

 x86_64-w64-mingw32-gcc -std=c++23 -fmodules-ts -x c++-system-header -c cstdint variant exception
x86_64-w64-mingw32-gcc -std=c++23 -fmodules-ts -lstdc++ -x c++ -c error.cppm -o error.o
x86_64-w64-mingw32-gcc -std=c++23 -fmodules-ts error.o main.cpp -lstdc++ -static-libstdc++ -o test.exe
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccztFNJq.o:main.cpp:(.text+0x0): multiple definition of `Crash@Error::~Crash()'; error.o:error.cppm:(.text$_ZNW5Error5CrashD1Ev[_ZNW5Error5CrashD1Ev]+0x0): first defined here
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccztFNJq.o:main.cpp:(.text+0x2e): multiple definition of `Crash@Error::~Crash()'; error.o:error.cppm:(.text$_ZNW5Error5CrashD0Ev[_ZNW5Error5CrashD0Ev]+0x0): first defined here
collect2.exe: error: ld returned 1 exit status

If I explicitly create a default or empty destructor for Crash, the error does not change.

The exception was created as per this file:

error.cppm

export module Error;

import <cstdint>;
import <exception>;

export enum class ErrorCode: uint8_t {
    INVALID,
    PROBLEM1,
    PROBLEM2,
};

export class Crash: public std::exception {
    public:
        Crash(ErrorCode crashCode) noexcept: code(crashCode) { }

    private:
        ErrorCode code;
};

The main file I used to test just throws the exception.

main.cpp

import Error;

int main() {
    throw Crash(ErrorCode::PROBLEM1);
}

Is this just something I can't do yet, or have I made a fundamental mistake in my code? Could it be because I haven't put the module code in a namespace?


Solution

  • Your code looks sound, and is compiling, linking and working properly with g++ 14.2 on a 64-bit Debian.

    It is very likely that your issue is specific to MinGW/MSYS, you should report them a bug.