关于在C中出现的循环引用问题, 目的希望学习到如何规避头文件循环引用出现的这类错误.
大概逻辑描述
main.c : 是程序入口,
a.h,b.h,c.h 为头文件;
其中
a.h 中 include c.h;
c.h include b.h ;
b.h include a.h
运行程序报错,
相关代码
main.c
#include <stdio.h>
#include "a.h"
int main(int argc, const char * argv[]) {
printf("Hello ! \n");
return 0;
}
a.h
#ifndef a_h
#define a_h
#include "c.h"
struct sem
{
struct eve *evet;
};
#endif /* a_h */
b.h
#ifndef b_h
#define b_h
#include "a.h"
struct pan
{
struct sem semt;
};
struct dev
{
int x;
};
#endif /* b_h */
c.h
#ifndef c_h
#define c_h
#include "b.h"
struct eve
{
struct dev *devt;
};
#endif /* c_h */
循环引用得从设计上去规避。
比如你的例子里根本原因是pan->sam->eve->dev的依赖,而pan和dev又放在同一个头文件里声明。
解决办法很简单,就是把dev和pan的声明分离开来就是了。
比较常见的做法就是前置声明+指针。
毕竟c++里要实现
是不可能的……