C:在文件之间传递变量

标签 c scope global

我试图将局部变量(在 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/

相关文章:

c - 将多个 C 文件解析为单个 AST 的工具/解析器

在每个页面上运行的 Angular6 应用程序逻辑

mysql - 如何将范围与子查询或 find_by_sql 链接或组合

javascript - 如何将数组/值传递给 Javascript 函数

C 在头文件中使 volatile sig_atomic_t 全局化

c - 如何编辑数组元素?

C 避免对齐问题

c++ - 在 C/C++ 中的特定地址边界上对齐内存是否仍能提高 x86 性能?

C:排序方法分析

javascript - JavaScript闭包如何工作?