5

プロジェクト (Visual Studio) に3 つの*.cファイル ( file1.cfile2.cおよびfile3.c) と 1 つの*.hファイル ( ) があります。file3.h

/*******************************
file3.h
********************************/
#ifndef FILE3_H
#define FILE3_H
int gintVariable = 400;
#endif


/*******************************
file1.c
********************************/
#include "file3.h"
#include <stdio.h>
#include <conio.h>

int modifyGlobalVariable(void);
void printGlobalVariable(void);

int main(void)
{
    modifyGlobalVariable();
    printGlobalVariable();
    printf("Global variable: %d\n", gintVariable++);
    getch();
    return 0;
}


/*******************************
file2.c
********************************/
#include "file3.h"                      

int modifyGlobalVariable(void) 
{ 
    return gintVariable++; 
}


/*******************************
file3.c
********************************/
#include "file3.h"
#include <stdio.h>

void printGlobalVariable(void)
{
    printf("Global: %d\n", gintVariable++);
}

VSでソリューションをビルドすると、エラーが発生し"_gintVariable already defined in file1.obj"ます。

プリプロセッサの出力を確認しました。インクルード ガードを含めたにもかかわらず、すべての *.c ファイルに gintVariable が含まれています。

私がしている間違いは何ですか?

4

2 に答える 2

4

ガードを含めることで、単一の翻訳単位に複数含まれる (より正確には、.h ファイルの内容を複数コンパイルする) ことを防ぎます。

この問題に対して役立ちます:

/* glob.h */
#ifndef H_GLOB
#define H_GLOB

struct s { int i; };

#endif


/* f.h */
#ifndef H_F
#define H_F

#include "glob.h"

struct s f(void);

#endif


/* g.h */
#ifndef H_G
#define H_G

#include "glob.h"

struct s g(void);

#endif


/* c.c */
#include "f.h" /* includes "glob.h" */
#include "g.h" /* includes "glob.h" */

void c(void) {
    struct s s1 = f();
    struct s s2 = g();
}

インクルージョンはダイヤモンドのようです。

    glob.h
   / \
ふふふ
   \ /
     cc
于 2013-08-21T12:14:59.867 に答える