【问题标题】:conflicting declaration for typedef when using C header in C++ application在 C++ 应用程序中使用 C 标头时 typedef 的声明冲突
【发布时间】:2022-08-09 13:53:58
【问题描述】:

有一个来自 C 库的头文件说 header1.h。 在 header1.h 中,

  31 enum ConnectionState {
  32     InProgress = 0,
  33     BannerWaitEol = 1,
  34     BannerDone = 2,
  35     Finished = 3,
  36 };
  37 typedef uint8_t ConnectionState;

我在我的 C++ 代码中使用它作为

extern \"C\"
{
#include \"header1.h\"
}

但我得到一个编译错误

header1.h:37:17: error: conflicting declaration \'typedef uint8_t ConnectionState\'
 typedef uint8_t ConnectionState;
                 ^~~~~~~~~~~~~~~~~~
header1.h:31:6: note: previous declaration as \'enum ConnectionState\'
 enum ConnectionState {
      ^~~~~~~~~~~~~~~~~~

我读了帖子:Conflicting declaration in c++。现在我明白这是 C 和 C++ 之间的 typedef 差异。 但我无法更改 header1.h 因为它来自第三方库。如何在我的 C++ 应用程序中使用这个 header1.h?谢谢您的帮助。

  • 这可能很棘手。你使用哪个编译器?
  • @Eng CA 最好的方法是不要使用这个糟糕的库。:)
  • 使用@tstanisl gcc6。

标签: c c++11 compiler-errors


【解决方案1】:

您可以使用 push_macro/pop_macro 编译指示将 ConnectionState 重新定义为其他名称并取消定义宏。

尝试这个:

// define ConnectionState as no-op
#define ConnectionState  ConnectionState
#pragma push_macro("ConnectionState")
#undef ConnectionState

// replace ConnectionState with ConnectionState_ and reset the macro to no-op
#define ConnectionState ConnectionState_ _Pragma("pop_macro(\"ConnectionState\")")

#include "header1.h"

它将转变:

enum ConnectionState {
    InProgress = 0,
    BannerWaitEol = 1,
    BannerDone = 2,
    Finished = 3,
};
typedef uint8_t ConnectionState;

进入这个:

enum ConnectionState_ {
    InProgress = 0,
    BannerWaitEol = 1,
    BannerDone = 2,
    Finished = 3,
};
typedef uint8_t ConnectionState;

只要没有人使用enum ConnectionState,就足以避免重新定义错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多