本文介绍了为什么当我将对象声明为静态时,错误LINK2005:对象已定义的错误消失了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在头文件中定义了以下结构和结构对象,如下所示:

I have the follwoing structure and object of structure defined in the header file as below:

struct STConfigurationDetails
{
    bool bAutoStart;
    bool bAutoLog;
    bool bAutoScan;
    bool bAutoMount;
    bool bAutoOpen;
    bool bAutoDetectLast;
};

struct STConfigurationDetails g_objConfigurationDetails ;

在头文件中,它本身具有方法和使用g_objConfigurationDetails的方法主体.当我将头文件包含到另一个cpp文件中并调用该方法时,此方法工作正常.但是,当我将头文件添加到另一个cpp文件的那一刻,我得到了错误:

In the header file it self I have both method and method body which is using g_objConfigurationDetails . This works fine when I include the header file to another cpp file and call the method. But the moment I added the header file to another cpp file I got the error:

错误2致命错误LNK1169:找到一个或多个乘法定义的符号d:\ FromClearCase \ Development_view \ NDS_11152010 \ exe \ Debug \ NDSClient.exe 1 NDSClient

Error 2 fatal error LNK1169: one or more multiply defined symbols found d:\FromClearCase\Development_view\NDS_11152010\exe\Debug\NDSClient.exe 1 NDSClient

搜索了几个线程后,我发现必须将我的对象声明为静态对象,并且可以解决.但是我想知道为什么仅在te头文件中创建实例时会出现多个实例错误.

After searching few threads I found out I have to declare my object as static and it solved. But I want to know why was I getting multiple instance error while I was creating the instance only in te header file.

这是因为我的头文件具有全局变量,并且包含在多个CPP中吗?

Is this because my Header File has a global variable and it is being included in multiple CPPs?

推荐答案

添加 static 可能会解决您的链接问题,但会给您带来更大的问题.该变量不再是全局变量,并且在使用该变量的每个CPP文件中具有不同的值.您需要在头文件中将其声明为 extern ,然后按原样在一个CPP文件中声明一次.

Adding static might solve your linking problem, but gives you a much bigger problem. That variable is no longer global and has a different value in every CPP file that uses it. You need to declare it as extern in the header file and then declare it one more time in just one CPP file as is.

当您使用 static 时,这意味着该变量将完全位于当前CPP文件的本地,并且不会暴露给其他文件.这就是链接器不再关心在另一个文件中是否存在另一个具有相同名称的静态变量的原因.它们是不同的变量.

When you use static it means the variable will be completely local to the current CPP file and will not be exposed to other files. That's why the linker no longer cares if there is another static variable in another file that has the same name. They are not the same variable.

如果要使用真正的全局变量,则必须在一个CPP文件中声明该变量,并且只有其原型(带有 extern )应位于与其他CPP文件共享的头文件中.就像函数一样-在一个文件中声明,为其余文件原型化.对于功能,您只是不提供主体.对于变量,请使用 extern .

If you want a truly global variable, it must be declared in exactly one CPP file and only its prototype (with extern) should be in a header file that will be shared with other CPP files. It's exactly like functions - declared in one file, prototyped for the rest. For functions, you simply don't provide a body. For variables, you use extern.

这篇关于为什么当我将对象声明为静态时,错误LINK2005:对象已定义的错误消失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:11