2016-09-19 141 views
-3

我有一个简单的程序,如:如何在C函数中使用全局变量包含在其他文件

int velocity=0; 

#include "extra.h" 

int main() 
{ 
    extra(); 
    return 0; 
} 

其中extra.h是:

void extra(){ 
    velocity += 1; 
} 

然而,当我编译此,我得到的错误:

extra.h:5:5: error: 'velocity' was not declared in this scope 

很明显,我在extra.h代码不能“看到”麦变量n.c,但为什么呢?我该如何解决?

+0

尝试把速度变量.h文件来代替。 – uvr

+2

@uvr这当然不是一个好的做法。 –

+0

http://stackoverflow.com/questions/10422034/when-to-use-extern-in-c – willll

回答

0

可以将以下声明添加到extra.h

extern int velocity; 

然而,extra()不应extra.h首先定义。如果extra.h包含在同一个二进制文件中的多个.c文件中,则会导致问题。以下是你应该拥有的一切:

extra.h

void extra(); 

extra.c

#include "extra.h" 

static int velocity = 0; 

void extra() { 
    velocity += 1; 
} 

main.c

#include "extra.h" 

int main() 
{ 
    extra(); 
    return 0; 
} 
相关问题