头文件中缺少typedef会导致编译错误

missing typedef in header file causes compile error

本文关键字:编译 错误 typedef 文件      更新时间:2023-10-16

我有一个头文件monitor.hpp,带有:

#ifndef MONITOR_HPP_
#define MONITOR_HPP_
typedef unsigned short abc_status_id_t;
struct monitor_update
{
    monitor_update(BYTE* data, size_t size) { /* implementation */ }
    BYTE* data;
    size_t dataSize;
};
class monitor_consumer 
{
public:
    virtual ~monitor_consumer() {};
    virtual void updated(const monitor_update& update) = 0;
};
#endif // MONITOR_HPP_

请注意,上面没有BYTE的typedef(长话短说),但使用的其他文件可能包括Windows.h或其他具有typedef'd BYTE的文件。

但我有一个类,我需要#包括头文件:

#ifndef BYTE
typedef unsigned char       BYTE;
#endif
#include "monitor.hpp"
class mymonitor  : public monitor_consumer 
{
public:
    void updated(const monitor_update& update) { }
};
int main() {
}

如果我评论掉#ifndef BYTE,那么我得到:

monitor.hpp(9): error C2061: syntax error : identifier 'BYTE'
monitor.hpp(10): error C2143: syntax error : missing ';' before '*'
monitor.hpp(10): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

define修复程序有效,我在编译和链接时没有遇到任何问题。但这是最好的方法吗。我还有什么其他选择?

您使用的某些标头似乎执行了#define BYTE <something>,这是一件相当不友好的事情。

您可以尝试了解是否可以删除或禁用#define(某些Windows标头允许您选择性地关闭其中的一部分)。

否则,您的解决方案是应对敌对环境的合理方式。另一种选择是

#undef BYTE
typedef unsigned char       BYTE;