【问题标题】:Linker LNK2005 Error链接器 LNK2005 错误
【发布时间】:2014-12-30 04:21:58
【问题描述】:

我已经在这里搜索了很多次,但作者通常没有提供代码示例,我今天遇到了这个问题,我不太确定如何解决它。

1 个错误列表 bool Init(?@@A_NA) already defined in Client.obj。这是我的 Client.cpp、Main.cpp 和 Main.h 的部分代码。

客户端.cpp

#include "stdafx.h"
#include "Main.h"
// the rest of the code doesn't have anything to do with this error..

Main.h

#include "stdafx.h"
bool Init;
// the rest of the code doesn't have anything to do with this error..

Main.cpp

#include "stdafx.h"
#include "Main.h"

int main()
{
    Init = false;
    return 0;
}

【问题讨论】:

    标签: c++ visual-studio-2010 linker


    【解决方案1】:

    #include "Main.h" 中,您已经定义了bool Init;,因此每次包含Main.h,您都会重新定义Init。如果你将Init设为静态,

    static bool Init;
    

    这里Init 将具有页面级范围,您的代码应该可以正常工作。

    或者更好,你在Math.h中创建Init extern,

    extern bool Init;
    

    然后在 .cpp 文件中定义它,这样你就会有多个声明,但只有一个定义。

    【讨论】:

    • 如果必须使用全局变量,最好将它放在头文件中并在一个 cpp 文件中定义。
    • @RetiredNinja 不过,它会干扰其他全局 Init,您的方法通常是正确的,但 OP 的客户端库已经定义了 Init
    • 我看他根本没有使用图书馆。他显然有两个 cpp 文件和一个在标头中声明的变量,这会导致多重定义错误。如果将其设为静态,则错误将消失,但每个 cpp 文件将具有不同的变量。如果你将它外部化并在一个地方定义它,那么两者共享同一个变量。
    • 谢谢!这解决了它。我现在记得我之前遇到了这个错误,并且通过将变量设置为静态它开始工作。再次感谢:)
    • @RetiredNinja 只看代码你能看到链接了哪些库吗?没有。
    猜你喜欢
    • 2022-01-13
    • 2011-10-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多