How to solve Multiple definition errors in gcc linux?

10,514

Solution 1

Don't force a completely static link (don't use the -static flag) -- doing so on any modern UNIX system is an extremely bad idea(TM).

Instead, link just the libduma statically. Either of these commands should work:

g++ ./testDuma.cpp -g -pthread -o testDuma /path/to/libduma.a
g++ ./testDuma.cpp -g -pthread -o testDuma -Wl,-Bstatic -lduma -Wl,-Bdynamic

Solution 2

Add -nodefaultlibs flag to not link to libc. Or, remove -lduma and link it dynamically after compilation with:

LD_PRELOAD=/usr/lib/libduma.so ./testDuma
Share:
10,514
SunnyShah
Author by

SunnyShah

I solve machine learning problems with Java, R, JS, C++.

Updated on June 09, 2022

Comments

  • SunnyShah
    SunnyShah 7 months

    I am facing below errors when trying to statically link libDuma, Can you tell me how to ask g++ to use malloc from libDuma?

    [email protected]:~/CodeTest$ g++ ./testDuma.cpp -g  -o testDuma -static -lduma -pthread
    /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/libc.a(malloc.o): In function `free':
    (.text+0x4b00): multiple definition of `free'
    /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/libduma.a(duma.o):(.text+0x25f0): first defined here
    /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/libc.a(malloc.o): In function `malloc':
    (.text+0x4bc0): multiple definition of `malloc'
    /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/libduma.a(duma.o):(.text+0x2730): first defined here
    /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/libc.a(malloc.o): In function `realloc':
    (.text+0x5950): multiple definition of `realloc'
    /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/libduma.a(duma.o):(.text+0x23d0): first defined here
    collect2: ld returned 1 exit status
    
  • SunnyShah
    SunnyShah over 11 years
    with -nodegaultlibs it is not compiling, I need to statically link libDuma and it is compulsory for me, here are the errors I am getting pastebin.com/ydrdqN0J
  • Piotr Praszmo over 11 years
    @SunnyShah: I'm not sure if it will work correctly, but try -z muldefs linker flag. Like: g++ testDuma.cpp -static -g -o testDuma -lduma -lpthread -Xlinker -z -Xlinker muldefs
  • SunnyShah
    SunnyShah over 11 years
    Thanks for response, one doubt, any idea on how to ask G++ to use the symbols from duma and not from libc?