VC编程中经常能遇到LNK2005错误解决办法

来源:互联网 发布:mysql 自定义函数 编辑:程序博客网 时间:2024/05/02 09:05
使用VC编程中经常能遇到LNK2005错误——重复定义错误,其实LNK2005错误并不是一个很难解决的错误。弄清楚它形成的原因,就可以轻松解决它了。 

出现LNK2005错误有多种原因:
1.重复定义全局变量。
2.头文件的包含重复。
3.使用第三方的库造成的。

这 里只讨论使用第三方的库造成的原因的处理。如果在程序中同时使用了多个函数库,并且这些函数库中有些函数名称有冲突,就会引起LNK2005错误。微软提 供了两套C运行期函数库,一种是普通的函数库:LIBC.LIB,不支持多线程。另外一种是支持多线程的:msvcrt.lib。如果一个工程里,这两种 函数库混合使用,可能会引起这个LNK2005错误,一般情况下它需要MFC的库先于普通运行期函数库被连接,因此建议使用支持多线程的 msvcrt.lib。
通常是尽量避免这样混合使用两套函数库(LIBC.lib和MSVCRT.lib)。如果不得不同时使用两套函数库或者其它相互有冲突的函数库,可以尝试按下面所说的方法:

在编译包含zlib库文件的时候,出现以下错误:
Linking...
MSVCRT.lib(MSVCRT.dll) : error LNK2005: _malloc already defined in LIBCD.lib(dbgheap.obj)
MSVCRT.lib(MSVCRT.dll) : error LNK2005: _sprintf already defined in LIBCD.lib(sprintf.obj)
MSVCRT.lib(MSVCRT.dll) : error LNK2005: _fclose already defined in LIBCD.lib(fclose.obj)
MSVCRT.lib(MSVCRT.dll) : error LNK2005: _free already defined in LIBCD.lib(dbgheap.obj)
MSVCRT.lib(MSVCRT.dll) : error LNK2005: __vsnprintf already defined in LIBCD.lib(vsnprint.obj)
MSVCRT.lib(MSVCRT.dll) : error LNK2005: _fflush already defined in LIBCD.lib(fflush.obj)
LINK : warning LNK4098: defaultlib "MSVCRT" conflicts with use of other libs; use /NODEFAULTLIB:library
Debug/Test.exe : fatal error LNK1169: one or more multiply defined symbols found

产生的原因是一个函数在两个不同的Lib中都有导出(MSVCRTD和LIBC有冲突),有两种办法处理:
方法一: MSDN对此的解决方法是增加[/FORCE:MULTIPLE]连接选项. 这方式发现会有警告,但可以编译通过:
LINK : warning LNK4075: ignoring /INCREMENTAL due to /FORCE specification
MSVCRT.lib(MSVCRT.dll) : warning LNK4006: _malloc already defined in LIBCD.lib(dbgheap.obj); second definition ignored
MSVCRT.lib(MSVCRT.dll) : warning LNK4006: _sprintf already defined in LIBCD.lib(sprintf.obj); second definition ignored
MSVCRT.lib(MSVCRT.dll) : warning LNK4006: _fclose already defined in LIBCD.lib(fclose.obj); second definition ignored
MSVCRT.lib(MSVCRT.dll) : warning LNK4006: _free already defined in LIBCD.lib(dbgheap.obj); second definition ignored
MSVCRT.lib(MSVCRT.dll) : warning LNK4006: __vsnprintf already defined in LIBCD.lib(vsnprint.obj); second definition ignored
MSVCRT.lib(MSVCRT.dll) : warning LNK4006: _fflush already defined in LIBCD.lib(fflush.obj); second definition ignored
LINK : warning LNK4098: defaultlib "MSVCRT" conflicts with use of other libs; use /NODEFAULTLIB:library


方法二:添加链接选项:/NODEFAULTLIB:<library> 如:/nodefaultlib:"libcd.lib"  该方法能编译通过,并且没有警告。

【可以在文件开始处加入#pragma comment(linker, "/NODEFAULTLIB:<library>")就可以了,不用到工程设置里去设置】

原创粉丝点击