是否有可能#Include 在“钻石继承"中?结构体? [英] Is it possible to #Include in a "diamond inheritance" structure?

查看:19
本文介绍了是否有可能#Include 在“钻石继承"中?结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 C 编写一些项目.

I'm trying to make some project in C.

我想知道是否可以从同一个文件中制作两次 #include,以一种让人想起钻石遗产的方式.

I would like to know if it is possible to make #include from the same file twice, in a way that recalls diamond heritage.

  • a.c中有#include "a.h"
  • b.c中有#include "b.h"
  • b.h中有#include "a.h"
  • in a.c there is #include "a.h"
  • in b.c there is #include "b.h"
  • in b.h there is #include "a.h"

是否可以在a.c#include "b.h"?

我收到一个错误:

some_variable already defined in a.obj

推荐答案

简单:不要在标题中定义变量,只需声明它们:

Simple: don't define variables in headers, just declare them:

标题:

// 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 守卫很有用,也是一个养成的好习惯,但它们可能不是解决这个特定问题的方法.

As others have mentioned, #include guards are useful, and a good habit to get into, but they are probably not the solution for this specific problem.

这篇关于是否有可能#Include 在“钻石继承"中?结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆