c++ - 创建全局变量导致链接器错误

标签 c++ mfc linker compiler-errors global-variables

我有一个 MFC 应用程序 AVT_testapp,在头文件 (AVT_testappDlg.h) 中,我试图在所有函数、类等之外创建一个变量,以使其成为全局变量。每当我尝试这样做时(比如我尝试 int x = 7),我都会收到错误消息:

1>AVT_testappDlg.obj : error LNK2005: "int x" (?x@@3HA) already defined in 
    AVT_testapp.obj
1>..\..\bin\x64\Debug\AVT_testapp.exe : fatal error LNK1169: one or more 
    multiply defined symbols found

我在谷歌上找到的所有内容都说“只需添加 header 保护”。 AVT_testappDlg 有 6 个 #include,每个都有 header 保护。

创建全局变量时还有什么可能导致这些错误?

编辑:这是我的头文件的开头,

#pragma once

#include "../../src/CoreUtils/nierr.h"
#include "..\..\src\CoreUtils\StringHelpers.h" //includes windows.h
#include "afxwin.h"
#include "afxcmn.h"
#include "IFrameObserver.h"
#include "c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\GdiPlusHeaders.h"
//#include <fstream>
//#include <windows.h>

int x = 7;

using namespace AVT::VmbAPI;


//////////////////////////////////////////////////////////////////////////
//////////  MyObserver class   ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
class MyObserver : public IFrameObserver
{
private:
    MyObserver( MyObserver& );

    MyObserver& operator=( const MyObserver& );    

public:

    VmbUchar_t* imageData;

            //...
            //...
            //...
            //...

//that's the end of the relevant stuff

最佳答案

您不能在 header 中的命名空间级别定义变量。一般来说,最好不要有全局变量,但如果需要,您应该只在 header 中提供一个声明,并在单个 .cpp 中提供定义:

//header
extern int i;

//cpp
int i;

您的代码问题与 header 防护无关。 header 保护确保 header 在每个翻译单元中只被解析一次。缺少 header 保护会导致编译器错误,编译器会在预处理后看到例如一个类在同一个翻译单元中定义多次。在您的情况下,错误是链接器错误 LNK2005,这意味着在多个翻译单元中定义了相同的符号(在您的情况下,每个翻译单元都包含带有定义的 header )。

关于c++ - 创建全局变量导致链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14855915/

相关文章:

c++ - native 使用程序集引用

C++ 可变参数模板

c++ - 如何在 VC++/MFC 应用程序中根据当前 DPI 设置缩放字体大小?

C++ : Difference between linking library and adding include directories

c++ - 两个宏之间重复运算的效率

c++ - C++中程序执行时带cout和不带cout的时间差

sockets - 如何通过套接字发送CString?

events - 即使添加 ON_COMMAND 处理程序后,菜单项仍保持禁用状态

c - 在运行时链接和加载共享库

C++模板基础程序,链接器找不到构造函数和析构函数