且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有可能在A&QUOT需要#include;菱形继承"结构体?

更新时间:2023-02-15 20:14:29

简单:没有的确定的头文件中的变量,只是声明的他们:

标题:

  // A.H的#ifndef A_H //经常使用的#include卫士
#定义A_HEXTERN INT my_variable; //声明my_variable...#万一

来源文件交流转换器:

  //交流转换器#包括A.HINT my_variable; //定义my_variable...

来源文件b.c:

  //交流转换器#包括A.H
#包括b.h...

正如其他人所说,后卫的#include是有用的,和良好的习惯进入,但他们可能不会为这一特定问题的解决方案。

I'm trying to make some project in C.

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

i.e.

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

Is it possible to #include "b.h" in a.c?

I get an error:

some_variable already defined in a.obj

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

Header:

// a.h

#ifndef A_H             // always use #include guards
#define A_H

extern int my_variable; // declare my_variable

...

#endif

Source file a.c:

// a.c

#include "a.h"

int my_variable;        // define my_variable

...

Source file b.c:

// a.c

#include "a.h"
#include "b.h"

...

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.