【发布时间】:2016-02-24 21:20:19
【问题描述】:
我一直在阅读有关标头保护及其用于解决重新定义错误的信息,但我不太确定如何正确实施它。这是我正在尝试做的一个简化示例:
fileA.h
#include first_header.h
#include second_header.h
// code here
文件B.h
#include first_header.h
#include second_header.h
// code here
mainfile.cpp
#include fileA.h
#include fileB.h
// code here
现在问题出现在 mainfile.cpp 中,因为我需要同时包含 fileA.h 和 fileB.h 标头,但是它们中的每一个都包含相同的标头引用,因此给了我重新定义错误。在这种情况下,我不确定如何绕过它或正确实施标头保护。
【问题讨论】:
-
如果未定义,您可以使用 #ifndef 等预处理器语句。
-
如果
first_header.h和second_header.h有包含保护,应该没有问题。在mainfile.cpp中,编译器会打开fileB.h,然后打开first_header.h,意识到定义了include头定义,忽略文件中的所有内容。 -
请提供minimal reproducible example。你没有显示 first_header.h 和 second_header.h 也没有说明他们有(或没有)他们自己的警卫。
标签: c++