2013-08-21 40 views
4

我有3個*.c文件(file1.cfile2.cfile3.c)和1個*.h文件(file3.h)在項目(Visual Studio中)。包括後衛仍然將全局變量

/******************************* 
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"

我確實檢查過預處理器的輸出,即使我已經包含了包含防護,gintVariable也包含在所有* .c文件中。

我在做什麼錯誤?

+2

你的錯誤是假設包括警衛對多個定義保護。出於好奇,是什麼給了你這個想法? –

+0

@LuchianGrigore:如果沒有包含,包含衛兵將只包含標題。我對麼? – OnlyQuestions

+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 
/ \ 
f.h  g.h 
    \ /
    c.c