Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;-多个文件中的全局变量_C++_Global Variables - Fatal编程技术网

C++ C++;-多个文件中的全局变量

C++ C++;-多个文件中的全局变量,c++,global-variables,C++,Global Variables,我在header.h中定义了变量“a”,并在test1.cpp和test2.cpp中使用它。 当我构建它时,我得到了一个链接错误,比如 致命错误LNK1169:找到一个或多个乘法定义符号 有什么问题吗? 我想使用全局变量“a”可以在多个cpp中使用 标题.h int a = 0; main.cpp #include "header.h" #include "test1.h" #include "test2.h" using namespace std; int _tmain(int arg

我在header.h中定义了变量“a”,并在test1.cpptest2.cpp中使用它。 当我构建它时,我得到了一个链接错误,比如

致命错误LNK1169:找到一个或多个乘法定义符号

有什么问题吗? 我想使用全局变量“a”可以在多个cpp中使用

标题.h

int a = 0;
main.cpp

#include "header.h"
#include "test1.h"
#include "test2.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    test1();    // expected output : 0
    test1();    // expected output : 1
    test2();    // expected output : 2
    test2();    // expected output : 3

    cout << "in main : " << a << endl;    // expected output : 3

    return 0;
}
test1.cpp

#include "test1.h"
#include "header.h"

void test1() {
    cout << "test1 : " << a << endl;
    a++;
}
test2.cpp

#include "test2.h"
#include "header.h"

void test2() {
    cout << "test2 : " << a << endl;
    a++;
}
#包括“test2.h”
#包括“header.h”
void test2(){

cout您应该只将
extern
声明放在一个头文件中。然后,该头文件应该包含在要使用
a
的任何其他文件中

然后,您应该将定义
int a=0;
放在一个实现文件(a
.cpp
文件)中


目前,您在多个头文件中有许多
extern
声明,这是可以的,但只是容易混淆。您应该只在一个位置声明它。然而,您的主要问题是您在
header.h
中定义了
a
。如果您在多个翻译单元中包含该头,您将有多个翻译单元定义。

您应该只在一个头文件中放入
extern
声明。然后,该头文件应该包含在任何其他要使用
a
的文件中

然后,您应该将定义
int a=0;
放在一个实现文件(a
.cpp
文件)中


目前,您在多个头文件中有许多
extern
声明,这是可以的,但只是容易混淆。您应该只在一个位置声明它。然而,您的主要问题是您在
header.h
中定义了
a
。如果您在多个翻译单元中包含该头,您将有多个翻译单元定义。

Post编译器选项,日志。Post编译器选项,日志。最好用正确的函数参数传输来替换这个全局。我希望test1和test2彼此不认识。@user1285975如果您不希望这些模块相互认识,您的体系结构在逻辑上是不正确的。在这种情况下,您必须将声明和定义放入新的第三个模块中,这是test1和test2都知道的。哦,我知道了。这太愚蠢了。谢谢。最好用适当的函数参数传输来替换这个全局函数。我希望test1和test2彼此不认识。@user1285975如果你不想让这些模块相互认识,你的arch它的结构在逻辑上是不正确的。在这种情况下,您必须将声明和定义放入新的第三个模块中,这是test1和test2都知道的。哦,我知道了。这太愚蠢了。谢谢。
extern int a;

void test2();
#include "test2.h"
#include "header.h"

void test2() {
    cout << "test2 : " << a << endl;
    a++;
}