bebbo / gcc

Bebbo's gcc-6-branch for m68k-amigaos
GNU General Public License v2.0
33 stars 11 forks source link

operator new() cannot be overloaded, when using -fno-exceptions; results in multiple definitions #211

Closed erique closed 9 months ago

erique commented 9 months ago

Considering the program

#include <stdio.h>
#include <stdlib.h>

/*
 /opt/amiga/bin/m68k-amigaos-g++ overloading_new.cpp -fno-exceptions 
*/

void* operator new(size_t size)
{
    void * p = malloc(size);
    printf("%s() allocating %zd bytes, returning %p\n", __FUNCTION__, size, p);
    return p;
}

void operator delete(void* p)
{
    printf("%s() freeing memory at %p\n", __FUNCTION__, p);
    free(p);
}

class TheClass
{
public:
    TheClass()
    {
        printf("Constructing %s()\n", __FUNCTION__);
    }
    ~TheClass()
    {
        printf("Destroying %s()\n", __FUNCTION__);
    }

    int some_value;
};

int main()
{
    TheClass* k = new TheClass();
    delete k;
    return 0;
}

When built using -fno-exceptions results in multiple definitions of operator new, like

$ /opt/amiga/bin/m68k-amigaos-g++ overloading_new.cpp -fno-exceptions
/opt/amiga/lib/gcc/m68k-amigaos/6.5.0b/../../../../m68k-amigaos/bin/ld: /opt/amiga/lib/gcc/m68k-amigaos/6.5.0b/new_op.o: in function `operator new(unsigned int)':
/opt/amiga/lib/gcc/m68k-amigaos/6.5.0b/new_op.o:(.text+0x10): multiple definition of `operator new(unsigned int)'; /tmp/ccPUpoyV.o:/tmp/ccPUpoyV.o:(.text+0x2a): first defined here
collect2: error: ld returned 1 exit status

If compiled without -fno-exceptions it succeeds and the resulting executable runs as expected.

Not sure if it's related, but, _GLIBCXX_WEAK_DEFINITION is "empty" when the new() implementation is compiled here https://github.com/bebbo/gcc/blob/287b715467ef4ef2bdca622471eb45707b4d110c/libstdc%2B%2B-v3/libsupc%2B%2B/new_op.cc#L41-L42

(symbol type is T and not W)

$ /opt/amiga/bin/m68k-amigaos-nm -C /opt/amiga/lib/gcc/m68k-amigaos/6.5.0b/new_op.o
         U abort
0000007c T __cxa_deleted_virtual
0000004e T __cxa_pure_virtual
         U malloc
         U perror
00000010 T operator new(unsigned int)
bebbo commented 9 months ago

can't reproduce:

was on amiga13.1 ...

btw: you are not overloading the operator, that's a redefinition.

erique commented 9 months ago

btw: you are not overloading the operator, that's a redefinition.

well, you're not wrong, but it is usually referred to as "global operator new/delete overloading" (says google :shrug: )

terminology aside - it seems to work now, thanks!