私はCでいくつかのプロジェクトを作ろうとしています。
#include
ダイヤモンドの遺産を思い起こさせる方法で、同じファイルから2回作成できるかどうか知りたいです。
すなわち
- ACにはあります
#include "a.h"
- 紀元前にあります
#include "b.h"
- bhには
#include "a.h"
AC#include "b.h"
で行うことは可能ですか?
エラーが発生します:
some_variable already defined in a.obj
簡単:ヘッダーで変数を定義せず、変数を宣言するだけです:
ヘッダ:
// a.h
#ifndef A_H // always use #include guards
#define A_H
extern int my_variable; // declare my_variable
...
#endif
ソースファイル ac:
// a.c
#include "a.h"
int my_variable; // define my_variable
...
ソースファイル bc:
// a.c
#include "a.h"
#include "b.h"
...
他の人が言及したように、 #include ガードは便利で、良い習慣ですが、おそらくこの特定の問題の解決策にはなりません。
ahextern
で変数を宣言し、ヘッダーahを次のように変更する必要があります。
#ifndef a_h
#define a_h
//your a.h
#endif