g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
我遇到了问题,而且我似乎发现了收到此错误的方法。
file statemachine.h
#ifndef STATEMACHINE_H_INCLUDED
#define STATEMACHINE_H_INCLUDED
#include "port.h"
enum state {
ST_UNINITIALIZED = 0x01,
ST_INITIALIZED = 0x02,
ST_OPENED = 0x03,
ST_UNBLOCKED = 0x04,
ST_DISPOSED = 0x05
};
void state_machine(event evt, port_t *port);
#endif /* STATEMACHINE_H_INCLUDED */
file port.h
#ifndef PORT_H_INCLUDED
#define PORT_H_INCLUDED
#include <stdio.h>
#include "statemachine.h"
struct port_t {
state current_state; /* Error 'state does not name a type */
.
.
};
#endif /* PORT_H_INCLUDED */
非常感谢任何建议,
答案 0 :(得分:7)
你可以在“statemachine.h”的“port.h”和“port.h”中加入“statemachine.h”吗?
尝试删除该行:
#include "port.h"
从文件“statemachine.h”
编辑(根据丹尼尔的评论):
然后您需要转发声明您的port_t
类型,如下所示:
...
ST_DISPOSED = 0x05
};
struct port_t;
void state_machine(event evt, port_t *port);
...
答案 1 :(得分:4)
你需要有另一个头文件,比如说,states.h
包含状态枚举。然后,port.h
和statemachine.h
都应包含该标头。
例如。
states.h
#ifndef STATES_H_INCLUDED
#define STATES_H_INCLUDED
enum state {
ST_UNINITIALIZED = 0x01,
ST_INITIALIZED = 0x02,
ST_OPENED = 0x03,
ST_UNBLOCKED = 0x04,
ST_DISPOSED = 0x05
};
#endif
答案 2 :(得分:1)
要打破循环依赖,请执行以下两项操作之一:
port.h
,而转发声明statemachine.h
移至void state_machine(event evt, port_t *port);
选择更有意义的内容。
要转发声明,请在port.h
:
statemachine.h
您仍然必须在#ifndef STATEMACHINE_H_INCLUDED
#define STATEMACHINE_H_INCLUDED
struct port_t;
enum state {
ST_UNINITIALIZED = 0x01,
ST_INITIALIZED = 0x02,
ST_OPENED = 0x03,
ST_UNBLOCKED = 0x04,
ST_DISPOSED = 0x05
};
void state_machine(event evt, port_t *port);
#endif /* STATEMACHINE_H_INCLUDED */
port.h
答案 3 :(得分:1)
相互包含的头文件在C ++中是个坏主意。作为包含机制,通过文本包含实现,然后您将发现结果文件中定义的顺序将取决于首先包含两个文件中的哪一个。因为在你的情况下,它们都依赖于另一个导出的符号,所以在使用时总会有一些符号(在你的情况下是类型)。
在您的情况下,我建议您将枚举移到另一个文件中。所以有一个state.h
文件:
#ifndef STATE_H_INCLUDED
#define STATE_H_INCLUDED
enum state {
ST_UNINITIALIZED = 0x01,
ST_INITIALIZED = 0x02,
ST_OPENED = 0x03,
ST_UNBLOCKED = 0x04,
ST_DISPOSED = 0x05
};
#endif /* STATE_H_INCLUDED*/
然后将statemachine.h
更改为:
#ifndef STATEMACHINE_H_INCLUDED
#define STATEMACHINE_H_INCLUDED
#include "port.h"
#include "state.h"
void state_machine(event evt, port_t *port);
#endif /* STATEMACHINE_H_INCLUDED */
和port.h
:
#ifndef PORT_H_INCLUDED
#define PORT_H_INCLUDED
#include <stdio.h>
#include "state.h"
typedef struct port_tag port_t;
struct port_tag {
state current_state; /* Error 'state does not name a type */
.
.
};
#endif /* PORT_H_INCLUDED */
现在,文件不是相互包含的,订单是明确定义的,一切都应该正常工作。