有一个来自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 {
^~~~~~~~~~~~~~~~~~
我读了这篇文章:c++中的冲突声明。现在我明白了这是C和c++之间的类型定义差异。但是我不能更改header1.h,因为它来自第三方库。我如何在我的c++应用程序中使用这个header1.h ?谢谢你的帮助。
您可以使用push_macro
/pop_macro
pragmas将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
,应该足以避免重定义错误。