【发布时间】:2017-04-04 00:11:02
【问题描述】:
我理解 extern 的方式是我们可以在程序的任何地方声明一个变量并使用它,但我们可以只定义一次。我在以下程序中遇到错误。
你好.c
#include <stdio.h>
#include "function.h"
extern int c;
int main()
{
int c;
c=10;
printf("%d\n",c);
printExternValue();
return 0;
}
函数.h
void printExternValue();
函数.c
#include "function.h"
#include "stdio.h"
extern int c;
void printExternValue()
{
printf("%d\n",c);
}
我希望这个程序能打印出来:
10
10
但它没有这样做,因为它给出了一个错误。我在 function.c 文件中重新声明了变量 c,目的是使用存储在所谓的外部存储中的值。
错误:function.c:(.text+0x6): undefined reference to `c'
我目前正在从 tutorialspoints 中读取 PDF 文件,我认为这是非常多余的,因为使用聚合 extern 创建变量的意图是无用的。应该这样做的正确方法是他们在函数外部定义变量对吗?
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
【问题讨论】:
-
您收到有关“未定义符号
c”的链接时错误?对于您显示的代码,您应该准确引用错误消息。在main()内部定义和引用的c与在main()外部声明的extern int c;无关。 -
是的,抱歉,我更新了帖子。
-
由于您的代码从未定义
c,因此找不到它也就不足为奇了。您需要一个int c;或int c = 314159265;或在您链接的文件之一中的函数之外的类似内容来创建程序。 -
好的,所以我在 main 中定义了 int c,但它超出了其他文件中定义的任何函数的范围。对吗?
-
不,你仍然需要在函数之外定义
c。
标签: c