C++定义全局变量的位置(链接器错误:符号已定义)

0 c++ linker symbols globals

我用Google搜索了大约30分钟,并没有发现任何与我的问题有关的内容:

我使用Visual Studio C++ 2008,它在我的头文件中声明了一个名为"stdafx.h"的标题我声明了我需要的所有东西,我想要全局变量也在那里,但是当我想要使用其中一个变量,我得到一个错误(在编译时)我的"stdafx.h"看起来像这样:

#pragma once

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
windows header here....

// C RunTime Header Files
compiler related standard headers here....


// TODO: reference additional headers your program requires here
#ifndef aaab
#include "codename.hpp"
#define aaab
#endif

// and a load of other headers (all of my project) followed here
...
...
...
Run Code Online (Sandbox Code Playgroud)

在声明后我定义了我的全局变量:

Game *game;
Run Code Online (Sandbox Code Playgroud)

我想在"codename.cpp"中使用它们

这里是班级的简短视图

#include "stdafx.h"
#define MAX_LOADSTRING 100
other class related stuff here....


main function here....


void test()
{
    game = new Game(); // HERE IS THE ERROR
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*son 9

您可能需要extern在头文件中声明全局:

extern Game *game;
Run Code Online (Sandbox Code Playgroud)

然后在.cpp文件中定义它.