我正在尝试用 C 语言做一些项目。
我想知道是否有可能从同一个文件中两次制作 #include
,以一种让人想起钻石传统的方式。
即
- 在a.c中有
#include "a.h"
- 在b.c中有
#include "b.h"
- 在b.h中有
#include "a.h"
是否可以在a.c中#include "b.h"
?
我得到一个错误:
some_variable already defined in a.obj
最佳答案
简单:不要在 header 中定义变量,只需声明它们:
标题:
// a.h
#ifndef A_H // always use #include guards
#define A_H
extern int my_variable; // declare my_variable
...
#endif
源文件 a.c:
// a.c
#include "a.h"
int my_variable; // define my_variable
...
源文件 b.c:
// a.c
#include "a.h"
#include "b.h"
...
正如其他人所提到的,#include 守卫很有用,也是一个养成的好习惯,但它们可能不是解决这个特定问题的方法。
关于c - 是否可以#Include 到 "diamond inheritance"结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13937523/