C++变量的多个定义

标签 c++ compiler-errors

我有 4 个文件(2 个标题文件和 2 个代码文件)。 文件A.cpp、文件A.h、文件B.cpp、文件B.h

文件A.cpp:

#include "FileA.h"

int main()
{
    hello();
    return 0;
}

void hello()
{
    //code here
}

文件A.h:

#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();

#endif /* FILEA_H_ */

文件B.cpp:

#include "FileB.h"

void world()
{
    //more code;
}

文件B.h:

#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();


#endif /* FILEB_H_ */

当我尝试编译(使用 eclipse)时,我得到“'multiple definition of `wat'” 而且我不知道为什么,它似乎应该工作得很好。

最佳答案

我不打算包括所有细节,但是您在编译 uint 中定义了一个全局变量 wat 两次。

要修复,请使用以下内容:

FileB.h

extern int wat;

FileB.cpp

int wat = 0;

这个 (extern) 告诉编译变量 wat 存在于某处,并且它需要自己找到它(在在本例中,它位于 FileB.cpp)

关于C++变量的多个定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44354857/

相关文章:

c++ - 迈耶斯单例范围

c++ - 无法在JGrasp中编译C++

syntax - 构造函数参数不匹配

c++ - 需要支持 OpenGL 的跨平台 GUI 工具包

python - Boost.Python 向现有 PyObject 添加绑定(bind)(用于异常处理)

c++ - 在 C++ 中与复制构造函数作斗争

c - 如何确定数据是否已写入结构中的变量

C 错误 : braced-group within expression allowed only inside a function

compiler-errors - Fortran问题: Argument of “xx” is one type at (2) but is some other type at (1)

C++ 抽象类参数错误解决方法