8

何らかの理由で、ヘッダーガードを使用しているのに、ヘッダーファイル内に複数のコンテンツ宣言があります。私のサンプルコードは以下のとおりです。

main.c:

#include "thing.h"

int main(){
    printf("%d", increment());

    return 0;
}

things.c:

#include "thing.h"

int increment(){
    return something++;
}

things.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

int something = 0;

int increment();

#endif

これをコンパイルしようとすると、GCCはsomething変数の定義が複数あると言います。ifndefはこれが起こらないことを確認する必要があるので、なぜそうなるのか混乱しています。

4

6 に答える 6

12

インクルード ガードは正しく機能しており、問題の原因ではありません。

インクルードするすべてのコンパイル単位がthing.h独自のを取得するint something = 0ため、リンカーは複数の定義について不平を言います。

これを修正する方法は次のとおりです。

こと.c:

#include "thing.h"

int something = 0;

int increment(){
    return something++;
}

こと.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

extern int something;

int increment();

#endif

このように、 のみthing.cが のインスタンスを持ち、somethingそれmain.cを参照します。

于 2011-10-28T07:24:57.157 に答える
4

各翻訳単位に1つの定義があります(に1つ、main.cに1つthing.c)。ヘッダーガードは、ヘッダーが単一の変換ユニットに複数回含まれるのを防ぎます。

関数と同じように、ヘッダーファイルで宣言し、でのみ 定義する必要があります。somethingthing.c

things.c:

#include "thing.h"

int something = 0;

int increment(void)
{
    return something++;
}

things.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

extern int something;

int increment(void);

#endif
于 2011-10-28T07:25:09.897 に答える
4

ヘッダーガードは、ファイルが同じコンパイル単位(ファイル)で複数回コンパイルされるのを防ぎます。main.cとthing.cに含めるので、それぞれで1回コンパイルされ、変数somethingが各ユニットで1回、または合計で2回宣言されます。

于 2011-10-28T07:25:41.730 に答える
1

変数は、ヘッダーファイルではなく、ファイルでsomething定義する必要があります。.c

ヘッダーファイルには、変数と関数プロトタイプの構造、マクロ、型宣言のみを含める必要があります。あなたの例では、ヘッダーファイルのsomethingようにタイプを宣言できます。extern int somethingただし、変数自体の定義は.cファイルに含める必要があります。

これまでに行ったことにより、変数はを含むファイルでsomething定義され、GCCがすべてをリンクしようとすると、「複数回定義されたもの」というエラーメッセージが表示されます。 .cthing.h

于 2011-10-28T07:30:02.557 に答える
1

try to avoid defining variables globally. use functions like increment() to modify and read its value instead. that way you can keep the variable static in the thing.c file, and you know for sure that only functions from that file will modify the value.

于 2011-10-28T07:33:02.933 に答える
0

ifndefガードしているのは複数回.hに含まれるものです.c。例えば

もの。時間

#ifndef
#define

int something = 0;
#endif

thing2.h

#include "thing.h"

main.c

#include "thing.h"
#include "thing2.h"
int main()
{
  printf("%d", something);
  return 0;
}

省略した場合ifndefGCCは文句を言います

 In file included from thing2.h:1:0,
             from main.c:2:
thing.h:3:5: error: redefinition of ‘something’
thing.h:3:5: note: previous definition of ‘something’ was here
于 2011-10-28T07:37:51.857 に答える