首页 >后端开发 >C++ >为什么多次包含头文件会导致 C 中的'多重定义”错误?

为什么多次包含头文件会导致 C 中的'多重定义”错误?

Barbara Streisand
Barbara Streisand原创
2024-12-27 17:00:11929浏览

Why Does Multiple Inclusion of a Header File Cause

C 中变量的多次定义

在 C 中,多次定义一个变量可能会导致编译错误。当多个文件包含头文件,导致同一变量有多个定义时,可能会出现此问题。

考虑以下场景:

// FileA.cpp
#include "FileA.h"

int main()
{
    hello();
    return 0;
}
// FileA.h
#ifndef FILEA_H_
#define FILEA_H_
void hello();
#endif
// FileB.cpp
#include "FileB.h"
// FileB.h
#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();
#endif

编译此代码时,您可能会遇到错误“multipledefinition of wat”,因为 FileA.h 和 FileB.h 都定义了变量wat`.

解决方案:

要解决这个问题,我们可以使用 extern 关键字。该关键字将变量声明为存在于程序中的其他位置,并防止它被多次定义。

// FileB.h
extern int wat;
// FileB.cpp
int wat = 0;

通过在 FileB.h 中将 wat 声明为 extern,我们实质上是告诉编译器wat 的定义存在于另一个文件中(本例中为 FileB.cpp)。这确保了不会有变量的多个定义,并允许编译顺利进行。

以上是为什么多次包含头文件会导致 C 中的'多重定义”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn