在其他文件中初始化的extern变量的编译错误

时间:2014-02-06 14:55:19

标签: c

我有两个不同的程序,我想从program2访问program1中声明的静态变量。

PROGRAM1。 (     / * file a.c * /)

#include<stdio.h>    

static int a = 100; /* global static variable not visible outside this file.*/
int *b = &a; /* global int pointer, pointing to global static*/

Program2

#include<stdio.h>
/* file b.c */
extern int *b; /* only declaration, b is defined in other file.*/

int main()
{
        printf("%d\n",*b); /* dereferencing b will give the value of variable a in file a.c */
        return 0;
}

虽然我编译program1,gcc a.c,没有编译错误,但是当我编译program2(gcc b.c)时,我收到了编译错误。

test_b.c:(.text+0x7): undefined reference to `b'
collect2: error: ld returned 1 exit status

为什么会出现编译错误?以下是计划static

的链接

提前致谢。

编辑1:

我打算使用其他程序的静态变量。我认为每个.c程序都必须有main()函数,只有.h程序有声明,我错了。所以我从a.c程序中删除了main()函数,而不是分别编译两个不同的程序,现在我根据Filip的建议使用gcc a.c b.c只编译一次。现在它工作正常。谢谢你们所有人。

3 个答案:

答案 0 :(得分:1)

嗯,你的代码已经说过了。 b.cpp只对所涉及的符号有声明,而不是定义。

由于这些显然是来自两个独立项目的源文件,我建议将您的定义移动到自己的 .cpp文件,然后可以在两个项目之间共享。 / p>

$ gcc a.c myIntPointerIsHere.c
$ gcc b.c myIntPointerIsHere.c

但是,有更清晰的方法可以在两个不同的项目之间共享代码。

答案 1 :(得分:0)

在编译a.c时,您必须与b.c相关联:

gcc a.c b.c

您不能指望链接器神奇地找到定义b的C文件。 extern表示它在别处定义 - 你必须说明在哪里。通过编译和链接a.c,链接器现在可以找到b的声明。

当然,您不能拥有2个main()功能。

答案 2 :(得分:-1)

这两个模块包含main的定义。似乎编译器没有在项目中包含第一个模块。否则我认为它会发出一个错误,主要被重新定义。

相关问题