Redefine malloc/free with static linking has multiple definition error

Recently, my company wants to update the compiler from gcc-3.4 to gcc-4.5. However, our customer's machine may not have the up-to-date libstdc++.so, so we want to static link our binary.

Our program needs customized malloc()/free() for very high performance requirement.

I modified the makefile, added a -static while linking, and got the following error message:

/usr/lib64/libc.a(malloc.o)(.text+0x18c0): In function `free':
: multiple definition of `free'
../../ic/src/memmgr/libmemmgr_mt_thread.a(memmgr_mt_thread.o)(.text+0x3430): first defined here
/usr/bin/ld: Warning: size of symbol `free' changed from 271 in ../../ic/src/memmgr/libmemmgr_mt_thread.a(memmgr_mt_thread.o) to 255 in /usr/lib64/libc.a(malloc.o)
/usr/lib64/libc.a(malloc.o)(.text+0x3970): In function `malloc':
: multiple definition of `malloc'
../../ic/src/memmgr/libmemmgr_mt_thread.a(memmgr_mt_thread.o)(.text+0x29c0): first defined here
/usr/bin/ld: Warning: size of symbol `malloc' changed from 281 in ../../ic/src/memmgr/libmemmgr_mt_thread.a(memmgr_mt_thread.o) to 461 in /usr/lib64/libc.a(malloc.o)
/usr/lib64/libc.a(malloc.o)(.text+0x4050): In function `realloc':
: multiple definition of `realloc'
../../ic/src/memmgr/libmemmgr_mt_thread.a(memmgr_mt_thread.o)(.text+0x3e80): first defined here
/usr/bin/ld: Warning: size of symbol `realloc' changed from 335 in ../../ic/src/memmgr/libmemmgr_mt_thread.a(memmgr_mt_thread.o) to 927 in /usr/lib64/libc.a(malloc.o)

Ok, it is reasonablle, since libc.a already has malloc()/free().

But what confuses me is why there is no error while dynamic linking. I searched, and found this question: How to redefine malloc() in Linux for use in C++ new. The answer says the linker treats library file(.a) and object file(.o) differently. Now I know the reason why the error happens with static linking but not with dynamic.

However, I tried the solution described in that answer, replaced the library file with the object file directly, but there is no difference. I still got the multiple definition linking error. I also tried -static-libgcc (because I don't know what to do, I just tried everything I saw in gcc man page) but it does not help, too.

I do not have to use static linking. I just want to solve the libstdc++.so version problem. Any suggestion will be appreciated.

Thanks in advance.

edit: Sorry I did not make myself clear. Using #define malloc ... may not help here. Since our program is C++. The #define idiom can only affact the malloc()/free() function. But our program acutally uses new/delete to allocate/free memory. Thanks anyway :D

7
задан Community 23 May 2017 в 12:23
поделиться