c++exceptionundefined-referencetypeinfo

C++ undefined reference to `typeinfo for int' when throwing exception without the standard library


For a project I'm working on, I'm writing a mini standard library replacement. For this, I'm currently trying to implement exceptions. So, I wrote the following minimal code

int memory[4];

void* __cxa_allocate_exception(long unsigned int thrown_size) throw()
{
    return memory;
}

void __cxa_free_exception(void * thrown_exception) throw()
{
    
}

void __cxa_throw(void* thrown_exception, void * tinfo, void (*dest)(void*))
{
    while(1){};
}

extern "C" void _start()
{
    throw 2;
}

However, when compiling this with -nostdlib, I get the following error

undefined reference to `typeinfo for int'

One of the big things throwing me off here, is what is 'typeinfo for int'??? It's not the name of a function, variable etc since it has spaces in it. Checking the compiler output in godbolt shows the following

 mov     esi, OFFSET FLAT:typeinfo for int

So I'm completely lost as to what it actually is!

Also, some answers seem to solve this by just including libstdc++ however this does not seem to work for me. I put the above code into godbolt, with the following compiler flags

-nostdlib -frtti -static-libstdc++

However I still get the same error and I'm not sure why. For reference, here is the code on godbolt showing said error.


Solution

  • So this was already answered by kakkoko's comment. But I just wanted to put this into an answer so that the question is marked as solved.

    So! Most compilers follow the Itanium abi, meaning that there is a defined interface. Essentially, when type_info and __fundamental_type_info are defined as the abi declares them (so matching the namespace, functions etc), then the compiler works some magic in the background and defines the type info for you!

    I tried to put this into godbolt, but it seems it needs them to be defined in a separate file.