基本C++重定义错误
Basic C++ Redefinition Error
我一直在阅读有关标头保护及其用于解决重定义错误的信息,但我不太确定如何正确实现它。以下是我正在尝试执行的操作的简化示例:
文件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
更便携。
相关文章:
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 使用命名空间时出现多个定义错误
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 在运算符重载定义中使用成员函数(const错误)
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在C++中使用内联方法时出现未定义的符号错误
- 已定义函数时出现 G++ "未定义的引用"错误
- C++ G++ 编译器 - 错误:隐式声明的定义
- 链接 cmake 时出现未定义的引用错误
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 错误:未定义对'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)'的引用
- 链接阶段出现多重定义错误
- 已经以性格错误定义了
- vim ctag导致了对乐趣的错误定义
- C++ 隐式声明的编译器错误定义
- 编译器错误-定义问题.C++