【问题标题】:Share global variable between .c file在 .c 文件之间共享全局变量
【发布时间】:2013-10-16 04:19:54
【问题描述】:

您好,我只是想知道如何在 .c 文件之间共享全局变量。
我尝试添加后续代码,但仍然出现错误。

test.c 文件

#include <stdio.h>

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

通过.h

extern int max;

通过.c

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

max;

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

    return 0;
}

但是当我编译passed.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)

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

【问题讨论】:

  • 你真的是说有两个 main() 函数吗?
  • 为什么有两个主要功能?它们是独立的程序还是要链接到一个程序中?如果它们在一个程序中链接在一起,它不应该抱怨 max - 它应该抱怨重复的主要功能。
  • 是的,我知道这可能是不可能的

标签: c global-variables declaration


【解决方案1】:

您可以在头文件中声明变量,例如假设在 declareGlobal.h-

//declareGlobal.h
extern int max; 

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

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

然后你可以在任何文件中使用这个变量——只要记住在声明它的头文件中包含它(即declareGlobal.c),例如,如果你想在passed.c中使用它,你可以执行以下操作:

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

【讨论】:

  • #include "declareGlobal.c" - 只是不要。
  • @H2CO3 我的意思是declareGlobal.h
  • 抱歉,您还需要在passed.c 中包含test.c(其中max 是实际定义和初始化的)文件。编辑了我的答案以反映变化。
【解决方案2】:

问题是你有两个程序,数据(如变量)不能简单地在程序之间共享。

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


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

然后在编译的时候把两个文件都传进去,比如

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

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

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多