Disabliing WPO / LTO with gcc / g++

  c++, g++, gcc

I want to prove that it is not possible to reliably throw exceptions through a C-function calling a C++-callback. That’s while with the older EH mechanism there’s no unwinding of the C function’s stack and with the newer table-driven EH there are no EH-tables for the return-addresses inside the C-function. This is the C++-source:

#include <iostream>
#include <exception>

using namespace std;

extern "C"
void callbackThunk( void (*)() );

int main()
{
    auto terminateHandler = []() -> void
    {
        cout << "terminated" << endl;
    };
    set_terminate( terminateHandler );
    auto callback = []() -> void
    {
        throw 123;
    };
    try
    {
        callbackThunk( callback );
    }
    catch( ... )
    {
        cout << "caught" << endl;
    }
}

This is the C-source:

#if defined(_MSC_VER)
__declspec(noinline)
#elif defined(__GNUC__)
__attribute((noinline))
#endif
void callbackThunk( void (*fn)() )
{
    fn();
}

With MSVC++ 2019 I’d have to disbale whole program optimization / link time code generation. With, the optimizer simply optimizes away the C-function and the C++-function is directly called from the C++-code "thinking" to call the callbackThunk-function. How do I prevent these interprocedural optimizations with gcc ?

Source: Windows Questions C++

LEAVE A COMMENT