头文件中的外部变量 [英] Extern variable in a header file

查看:204
本文介绍了头文件中的外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在了解外部变量。



我已声明一个名为
的变量


 int a = 10  



 int b = 10 

在源文件文件中.c



在file1.c



我使用

 extern int b; 





并使用printf打印变量b。



当我使用

 extern int a 

。它显示错误,说它无法找到引用的变量。是否与编译器或ANSI C有关,当使用extern时,它不会在头文件中查找引用?



我必须使用#includehead.h打印变量a。



任何人都可以解释它的ANSI或visual studio是否有问题?

解决方案

它应该是这样的:



foo。 h $>

  //  头文件foo.h  
// 声明a为全局变量
extern int a;





main.c

  //  主要源文件,其中包含实际变量a  
#include foo.h

int a; // 将变量声明为此模块的一部分





bar.c

  //  使用 
的值的其他源文件 #include < span class =code-string> foo.h //得到
的定义
void bar( int value
{
a + = value ;
}


问题既不是ANSI也不是VS.



你必须区分定义和代码之间(.c文件)和声明(在.h文件中)。



处理全局变量就像处理全局函数一样。在头文件中声明它们并在相应的源文件中定义它们:

  //  头文件啊 

// 全球可以从其他模块访问的变量。
// 不要在此处指定值。
extern int a;



  //  源文件ac  
#include

// 为全球分配价值变量。
int a = 10 ;



如果您现在想要在另一个模块中使用全局变量 a ,请包含头文件:

  //  文件bc  
#include ah

printf( a =%d \ n,a);





如果你输入''int a = 10; ''进入头文件,包含此头文件的每个文件都将拥有其自己的变量副本。然后它不是全局的,而是每个模块的本地。


Currently learning about the extern variable .

I have declared a variable called

int a=10

in a header file head.h

int b=10

in a source file file.c

In file1.c

I used

extern int b;



and printed the variable b using printf.

when i use

extern int a

.It shows an error saying it cannot find the referenced variable . Is it something to do with compiler or ANSI C that does not look up for references in header when extern is used?

I have to use #include "head.h" to print variable a.

Can anyone explain whether its ANSI or visual studio problem?

解决方案

It should be something like:

foo.h

// Header file foo.h
// declare a to be a global variable
extern int a;



main.c

// Main source file, which contains the actual variable a
#include "foo.h"

int a; // declare the variable as part of this module



bar.c

// other source file which uses the value of a
#include "foo.h" // gets the definition of a

void bar(int value)
{
    a += value;
}


The problem is neither ANSI nor VS.

You must differentiate between definitions and code (.c files), and declarations (in .h files).

Handle global variables just like handling global functions. Declare them in a header file and define them in the corresponding source file:

// Header file a.h

// A global variable that can be accessed from other modules.
// Don't assign a value here.
extern int a;


// Source file a.c 
#include "a.h"

// Assign value to global variable.
int a = 10;


If you now want to use the global variable a from within another module, include the header file:

// File b.c
#include "a.h"

printf("a = %d\n", a);



If you put something like ''int a = 10;'' into a header file, each file that includes this header file will have its''s own copy of the variable. Then it is not global, but local to each module.


这篇关于头文件中的外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆