对于C语言重复包含/重复定义的解决(gcc)

使用条件编译指令

例如:

a.h:
int fun();

b.h:
#include "a.h"

c.h:
#include "a.h"

main.c:
#include "b.h"
#include "c.h"

......
//编译时就会出现重复包含/定义错误

可以加入条件编译指令#ifndef #endif

​a.h:
#ifndef A_FUN
#define A_FUN
int fun();
#endif

b.h:
#include "a.h"

c.h:
#include "a.h"

main.c:
#include "b.h"
#include "c.h"

......
//编译时就会出现重复包含/定义错误

给出几个建议:

可以将要包含的头文件统一include到 .c/.cpp文件中,这样就会单独解析,不会发生错误。

或者直接include在头文件中,然后.c/.cpp文件里include自己的头文件,但头文件的函数要加上条件编译指令。例如:

b.h:
#include "a.h"
#include "c.h"

b.c:
#include "b.h"

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章