基本C++重定义错误

Basic C++ Redefinition Error

本文关键字:错误 定义 C++ 基本      更新时间:2023-10-16

我一直在阅读有关标头保护及其用于解决重定义错误的信息,但我不太确定如何正确实现它。以下是我正在尝试执行的操作的简化示例:

文件A.h

#include first_header.h
#include second_header.h
// code here

文件B.h

#include first_header.h
#include second_header.h
// code here

主文件.cpp

#include fileA.h
#include fileB.h
// code here

现在问题出在主文件中.cpp因为我需要同时包含 fileA.h 和 fileB.h 标头,但每个标头都包含相同的标头引用,因此给了我重新定义错误。在这种情况下,我不太确定如何绕过它或正确实现标头保护。

首先,您需要在文件名周围加上引号或尖括号,如下所示: #include <fileA.h>#include "fileA.h"

从您发布的内容来看,您似乎并不真正了解标题防护装置的工作原理。所以这是概要。

假设我有一个函数,我希望能够从不同的 c++ 文件调用它。您首先需要一个头文件。(您可以从包含保护内部执行包含。

#ifndef MYHEADER_HPP
#define MYHEADER_HPP
#include "first_header.h"
#include "second_header.h"
void MyFunction();
#endif

非包含预处理器行构成了所谓的"包含保护",您应始终保护头文件。

然后,您可以在.cpp文件中实现所述函数,如下所示:

#include "MyHeader.hpp"
void MyFunction()
{
    // Implementation goes here
}

现在,您可以在其他代码中使用此函数:

#include "MyHeader.hpp"
int main()
{
    MyFunction();
}
如果您使用的是 IDE 编译和链接,

则会为您处理,但为了以防万一,您可以使用 g++ 进行编译和链接(假设一个"main.cpp"文件和一个"MyFunction.cpp"文件):

g++ main.cpp -c
g++ MyFunction.cpp -c
g++ main.o MyFunction.o -o MyExecutable

我希望这有帮助,祝你好运!

逻辑:检查是否定义了特定的宏,如果未定义宏,请定义它并包含头文件的内容。这将防止重复包含标题内容。

喜欢这个:

文件 A:

#ifndef fileA_h
#define fileA_h
#include first_header.h
#include second_header.h
//code here
#endif

文件 B:

#ifndef fileB_h
#define fileB_h
#include first_header.h
#include second_header.h
//code here
#endif

大多数编译器(例如Visual Studio)也支持#pragma once,可以使用它来代替包含表示为"#ifndef"的守卫。你会发现在一些用MS Visual C++编写的遗留代码中。

然而,

#ifndef MYHEADER_HPP
#define MYHEADER_HPP
// code here
#endif

更便携。