【问题标题】:Include Guard still inserting Global Variables包括 Guard 仍然插入全局变量
【发布时间】:2013-08-23 18:07:37
【问题描述】:

我在一个项目 (Visual Studio) 中有 3 个 *.c 文件(file1.cfile2.cfile3.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,即使我已经包含了包含保护。

我做错了什么?

【问题讨论】:

  • 你的错误是假设包含保护防止多个定义。出于好奇,是什么让您产生了这个想法?
  • @LuchianGrigore:如果不包含,包含守卫将仅包含标题。我说的对吗?
  • 同一个翻译单元,是的。但是您正在编译多个文件,对吗?
  • @OnlyQuestions Include guards 在一个 .cpp 文件中工作。 它们防止在一个文件中包含多个标头,但在不同文件中不包含相同标头。
  • @Angew:哦,我现在明白了。谢谢。出于好奇,我想生成一个场景,其中单个文件发生多次包含。能给我举个例子吗?

标签: c global-variables include-guards


【解决方案1】:

包含保护可防止在单个翻译单元中多次包含(或更准确地说,是多次编译 .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();
}

内含物就像钻石:

全局文件 / \ f.h.h \ / 抄送

【讨论】:

    【解决方案2】:

    在头文件中声明全局变量时应使用“extern”。 在任何*.c 文件中定义它。 这应该可以解决问题。

    有关头文件的更多信息,请阅读 How do I use extern to share variables between source files?

    【讨论】: