【问题标题】:Header exclusion?标头排除?
【发布时间】:2015-12-14 04:25:16
【问题描述】:

简短说明:

Header.h#include <stdbool.h>,它有一个用于 c 中 _Bool 的宏。

file.cpp 包括 Header.h,但由于 file.cpp 是 C++ - 它具有 bool 作为本机类型。现在 lint 抱怨了一组由于这个原因(重新声明、不存在的方法等)。有没有办法防止在不接触Header.h 的情况下将<stdbool.h> 包含在file.cpp 中?

如果我对问题的描述看起来很荒谬 - 请向我扔西红柿 :) 否则,感谢您的帮助。

编辑: 现在再次想到这一点:了解编译和链接的基本概念我应该已经意识到在下游文件/头文件中“排除”某些头文件听起来很有趣,并且不应该没有杂物就不可能.但是,仍然感谢您的帮助。我理解这一点的另一个小砖头。

【问题讨论】:

  • 向您的图书馆供应商投诉。 stdbool.h 不应将 bool 和朋友定义为 C++ 中的宏。与此同时,#undef.
  • 可以修改header.h吗?然后只需在包含<stdbool.h> 之前添加对__cplusplus 的条件预处理器检查。你可能想看看你的 linter,它似乎不能很好地处理 C++,或者它不能很好地进行预处理。
  • @T.C.没那么简单,C++98 对<stdbool.h> 只字未提,所以它在 C++98 中的作用是不确定的。 GCC 的 <stdbool.h> 定义了 C++98 的宏,因为原因。蹩脚的理由。不过,它至少在 C++ 中是 #define bool bool,而不是 #define bool _Bool,这是非常有害的。
  • @JonathanWakely 与 #ifdef bool 的代码兼容,我猜?
  • @T.C.确切地说,尽管我不相信这样的代码足够普遍以迎合。请参阅gcc.gnu.org/ml/gcc-patches/2014-10/msg02594.html 了解一些历史。据我所知,没有任何后果,也许我应该重新审视它并尝试为 C++98 取消定义它们:)

标签: c++ c header-files lint


【解决方案1】:

您可以创建自己的stdbool.h 并将其放在包含路径的前面,以便在系统路径之前找到它。这在技术上是未定义的行为,但是您的 <stdbool.h> 已损坏,因此这是解决此问题的一种方法。你自己的版本可以是空的(如果它只包含在 C++ 文件中)或者如果你不能阻止它也被 C 文件使用,那么你可以这样做:

#if __cplusplus
# define __bool_true_false_are_defined   1
#elif defined(__GNUC__)
// include the real stdbool.h using the GNU #include_next extension
# include_next <stdbool.h>
#else
// define the C macros ourselves
# define __bool_true_false_are_defined   1
# define bool _Bool
# define true 1
# define false 0
#endif

更清洁的解决方案是在file.cpp 之前 包括Header.h

#include <stdbool.h>
// Undo the effects of the broken <stdbool.h> that is not C++ compatible
#undef true
#undef false
#undef bool
#include "Header.h"

现在,当 Header.h 包含 &lt;stdbool.h&gt; 时,它将不起作用,因为它已被包含在内。这种方式在技术上是无效的(见下面的评论),但在实践中几乎肯定可以移植。

它需要在每个包含Header.h 的文件中完成,因此您可以将其包装在一个新标题中并使用它来代替Header.h,例如CleanHeader.h 包含:

#ifndef CLEAN_HEADER_H
#define CLEAN_HEADER_H
// use this instead of Header.h to work around a broken <stdbool.h>
# include <stdbool.h>
# ifdef __cplusplus
// Undo the effects of the broken <stdbool.h> that is not C++ compatible
#  undef true
#  undef false
#  undef bool
#e ndif
# include "Header.h"
#endif

【讨论】:

  • 第二种方法在技术上违反了 [macro.names]/p2 :)
  • @T.C.哦!你说的很对,我会纠正我的说法,它是有效的。我认为这是最好的解决方案,因为尝试使用不符合标准的 std::lib 编写有效的 C++ 很困难!
猜你喜欢
  • 2021-04-30
  • 2020-05-03
  • 2019-10-01
  • 2013-07-20
  • 2018-09-12
  • 2022-11-18
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多