在.c文件之间共享全局变量

时间:2013-10-16 04:19:55

标签: c global-variables declaration

您好我想知道如何在.c文件之间共享全局变量 我尝试添加以下代码,但仍然会出错。

test.c文件

#include <stdio.h>

int max = 50;
int main() 
{
  printf("max %d", max); // result max 50
}

pass.h

extern int max;

passed.c

#include <stdio.h>
#include "pass.h"

max;

int main()
{    
    printf("pass %d \n", max);

    return 0;
}

但是当我编译pass.c时,我得到了跟随错误

Undefined symbols for architecture x86_64:
"_max", referenced from:
  _main in passed-iOMugx.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

有人可以帮忙吗?非常感谢你。

2 个答案:

答案 0 :(得分:2)

问题在于你有两个程序,而且只能在程序之间共享数据(如变量)。

您可能希望了解shared memory和其他inter-process communication方法。


另一方面,如果您只想拥有一个程序,并使用另一个文件中定义的变量,那么您仍然做错了。您在一个程序中只能有一个main函数,因此从其中一个源文件中删除main函数。同样在pass.c中,max;表达式无效,您也不需要它。

然后在编译时传递两个文件,如

$ clang -Wall -g test.c pass.c -o my_program

在上面的命令之后,你(希望)有一个名为my_program的可执行程序。

答案 1 :(得分:2)

您可以在头文件中声明变量,例如让我们在declareGlobal.h-

中说
//declareGlobal.h
extern int max; 

然后你应该在一个且唯一的文件中定义变量,例如让我们说,test.c。请记住包含声明变量的头文件,例如在这种情况下,declareGlobal.c

//test.c
#include "declareGlobal.h"
int max = 50;

然后,您可以在任何文件中使用此变量 - 只需记住将头文件包含在声明的位置(即declareGlobal.c),例如,如果要在pass.c中使用它,则可以执行以下操作:

//passed.c
#include <stdio.h>
#include "declareGlobal.h"
#include "test.c"
int main()
{
printf("pass %d \n", max);
return 0;
}
相关问题