C 未定义的引用错误。

5

以下是与代码相关的问题,特别是在header.c中,我无法访问头文件header.h中的extern int x变量…为什么?.h文件中的extern变量不是全局的吗?我该如何在其他文件中使用它?

===header.h===

#ifndef HDR_H
#define HDR_H

extern int x;
void function();

#endif

===header.c===

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

void function()
{
    printf("%d", x); //****undefined reference to x, why?****
}

===sample.c===

int main()
{
    int x = 1;
    function();
    printf("\n%d", x);
    return 0;
}

1
可能只需在您的主函数中删除 int 之前的 x。这将防止在主函数中创建一个与全局变量同名的新局部变量。 - bph
(已删除) - Michel Keijzers
请参阅有关extern int的更多信息,网址为[https://dev59.com/YlvUa4cB1Zd3GeqPw8o3][1]。 - Michel Keijzers
5个回答

9

The declaration

extern int x;

告诉编译器在某个源文件中会有一个名为x全局变量。然而,在main函数中,你声明了一个局部变量x。将该声明移到main函数之外,使其成为全局变量。


3
extern关键字表示变量已存在但不创建它。编译器期望另一个模块将具有该名称的全局变量,并且链接器会做正确的事情来连接它们。
您需要像这样更改sample.c:
/* x is a global exported from sample.c */
int x = 1;

int main()
{
    function();
    printf("\n%d", x);
    return 0;
}

1

extern声明一个变量,但不定义它。它基本上告诉编译器在其他地方有一个x的定义。要修复此问题,请将以下内容添加到header.c(或其他.c文件中,但仅限于一个.c文件):

int x;

请注意,在 main() 中,本地变量 x 会隐藏全局变量 x

1

实际上,extern int x; 表示 x 将在另一个地方/翻译单元中定义。

编译器期望在全局范围内的某个地方找到 x 的定义。


0
我会像这样重新组织/修改您的代码,并且摆脱header.c。

===sample.h===

#ifndef SAMPLE_H
#define SAMPLE_H

extern int x;
void function();

#endif

===sample.c===

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

int x;

void function()
{
    printf("%d", x);
}

int main()
{
    x = 1;
    function();
    printf("\n%d", x);
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接