如何解决gcc linux中的多个定义错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6080934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:11:16  来源:igfitidea点击:

How to solve Multiple definition errors in gcc linux?

linuxgccmultiple-definition-error

提问by SunnyShah

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

我在尝试静态链接 libDuma 时遇到以下错误,你能告诉我如何让 g++ 使用 libDuma 中的 malloc 吗?

sunny@sunny-laptop:~/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

采纳答案by Employed Russian

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

不要强制建立一个完全静态的链接(不要使用-static标志)——在任何现代 UNIX 系统上这样做都是一个非常糟糕的主意 (TM)。

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

相反,只静态链接 libduma。这些命令中的任何一个都应该有效:

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

回答by Piotr Praszmo

Add -nodefaultlibsflag to not link to libc. Or, remove -ldumaand link it dynamically after compilation with:

添加-nodefaultlibs标志以不链接到 libc。或者,-lduma在编译后动态删除并链接它:

LD_PRELOAD=/usr/lib/libduma.so ./testDuma