我试图将局部变量(在 func1 中)传递给另一个文件中的函数(func2),但 func2 要求将其作为全局变量。为了更好地解释事情,这里有两个文件:
文件1.c:
#include <something.h>
extern void func2();
void func1(){
int a=0;
func2();
}
文件2.c:
#include <something.h>
extern int a; //this will fail
void func2(){
printf("%d\n",a);
}
变量 int a
不能在 file1 中声明为全局变量,因为 func1 是递归调用的。有一个更好的方法吗?
最佳答案
在文件 1.c 中:
#include <something.h>
#include "file1.h"
int a;
void func1(){
a = 0;
}
在文件1.h中
extern int a;
在 file2.c 中:
#include <something.h>
#include "file1.h"
void func2(){
printf("%d\n",a);
}
所以:
- 变量在file1.c中
- file1.h让别人知道它的存在,而且它的类型是int。
- file2.c 包含 file1.h,以便编译器在 file2.c 尝试使用 var a 之前就知道它的存在。
关于C:在文件之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30042524/