3

我正在尝试使用来自分离的 .cpp 文件的全局变量。我有一个 init.h 文件:

//init.h
#ifndef init
#define init
int a = 3;
#endif

我有一个 init.cpp 文件: //init.cpp #include init.h

最后我的 main.cpp 文件是:

//main.cpp
#include "init.h"
int main(void)
{
    while(1)
    {
    }
}

在此之后,我收到错误:

1>init.obj : error LNK2005: "int a" (?a@@3HA) already defined in main.obj
1> ..deneme.exe : fatal error LNK1169: one or more multiply defined symbols found

为什么我的#infdef控件不能解决这个问题?我也尝试过使用#pragma once,但我得到了同样的错误。我的代码有什么问题?

4

1 回答 1

9

You need to mark your variable as extern and define it only once in an implementation file.

As the code is now, you're breaking the one definition rule. The include guards don't help in this case, since all translation units that include that header re-define the variable.

What you actually need:

//init.h
#ifndef init
#define init
extern int a;
#endif

and the definition:

//init.cpp
#include "init.h"
int a = 3;

Also, think twice before using globals. What is it that you're actually trying to achieve?

于 2012-04-13T12:38:26.453 回答