多个定义和未定义的引用

时间:2016-09-07 09:44:47

标签: c++

我的C ++代码在编译时会出现许多“多重定义”错误。我的情况的一个最小例子是:

//testA.h
#ifndef __FILEA_H_INCLUDED__
#define __FILEA_H_INCLUDED__

int A;
int B;

#endif

//testB.h
#ifndef __FILEB_H_INCLUDED__
#define __FILEB_H_INCLUDED__

int C;
int D;

#endif

//testA.cpp
#include "testA.h"

//testB.cpp
#include <iostream>
#include "testA.h"
#include "testB.h"

int main() {
    std::cout << C << std::endl;
}

在变量声明中加上“extern”解决了这些“多重定义”错误,但引入了“未定义的引用”错误。我已经尝试了所有我能想到的解决方案 - 但显然我做错了。

如果您想知道,在我的实际应用程序中,我需要将变量视为全局变量。

1 个答案:

答案 0 :(得分:1)

您应该在.h文件中声明全局变量,并在.cpp文件中定义它们。

  

在testA.h中

extern int A;

  

在testA.cpp中

int A;