C++包括标头在内的多个定义

multiple definition in C++ including header

本文关键字:定义 包括标 C++      更新时间:2023-10-16

我有一个有多个文件的项目,如下所示:

//header.h
class example {...}
//variable.h
#include "header.h"
example ex;
//main.cpp
#include "variable.h"
....
//src1.cpp
#include "variable.h"

编译编译器错误时:多重定义"ex" 我不明白为什么,我想在main中使用"ex".cpp src1.cpp,我该怎么办。 谢谢

通过main.cppsrc1.cpp#includingvariable.h,你已经定义了变量ex两次。链接器(不是编译器(不会喜欢这样。

相反,请将variable.h更改为如下所示:

extern example ex;

并把:

example ex;

在(说(src1.cpp

.是的,使用也包括警卫,但这不是这里的问题。

在 header.h 和 variable.h 中使用 include guards:

#ifndef HEADER_H
#define HEADER_H
class header {...}
#endif