C #include 循环引用问题, 头文件循环引用

关于在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 */

期待给出自己遇到的关于头文件循环引用的例子和解决方法,有理有据;之所以问题发出来希望帮助更多遇到类似问题的人,同时希望答案相对全面一些.

阅读 12.8k
2 个回答

循环引用得从设计上去规避。
比如你的例子里根本原因是pan->sam->eve->dev的依赖,而pan和dev又放在同一个头文件里声明。
解决办法很简单,就是把dev和pan的声明分离开来就是了。

比较常见的做法就是前置声明+指针。

毕竟c++里要实现

class A
{
    B b;
};
class B
{
    A a;
};

是不可能的……

例子1

说明: header1.h 包含 header2.h; header2.h 包含 header1.h;

/** circular dependency -- 测试循环引用 */
#include <stdio.h>
#include "header1.h"

int main(void) {
    printf("this is my function!");
    return 0;
}

header1.h

#ifndef Header1_H_
#define Header1_H_

#include "header2.h"

/*
=========header2.h=======

========header1.h======
#include <header1.h>
再次把 header1.h 展开
#ifndef Header1_H_
#define Header1_H_
由于已经 定义过header1_H_ ;所以其中代码不会执行;
// Other content
#endif  
========header1.h=====

struct A2{
    int value;
};

=========header2.h=========

*/

/**
 *  下面的类型如果是 指向 A2 结构体的指针; 可以不引用 header2.h 头文件; eg: struct A2 *p;
 *  也可写成 void * p ;
*/


/**
 * 下面变量定义必须需要知道A2的值,所以需要引入头文件 
*/
struct A1 {
    int value;
    struct A2 p;
};

#endif 

header2.h

#ifndef Header2_H_
#define Header2_H_

#include "header1.h"

struct A2{
    int value;
};

#endif

这里通过 #ifndef X_H_ #define X_H_ #endif 来解决;

[原文参考]https://stackoverflow.com/que...

[Headers and Includes: Why and How]http://www.cplusplus.com/foru...

[Avoiding Circular Dependencies of header files
]https://stackoverflow.com/que...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题