我如何为C头文件中声明的extern结构赋值或对其进行修改?

问题描述 投票:0回答:2

我在头文件aba.h中声明了2个termios结构:

extern struct termios cookedInput, rawInput;

然后在一个函数中,我试图像这样更改stdin_prep.c中的值:

tcgetattr(STDIN_FILENO, &cookedInput);
rawInput = cookedInput;
cfmakeraw(&rawInput);

gcc -Wall -Werror -Wextra *.c给我以下错误:

In function stdin_change.c
stdin_change.c:(.text+0x26): undefined reference to 'rawInput'
stdin_change.c:(.text+0x55): undefined reference to 'cookedInput'

这些功能stdin_prep();stdin_change("raw");在我的main.c中被调用。

我尝试了以下几种解决方案:Undefined reference to global variable during linkingC: undefined reference to a variable when using extern,但出现了许多不同的错误。

我已经包括了我的终端机的图片。WSL-Ubuntu-18.04-Screenshot

c gcc extern undefined-reference termios
2个回答
3
投票

声明一个对象不会导致它存在。您需要实际定义它。放

struct termios rawInput;

可选地,使用初始化程序在顶层.c文件中的顶级(不在任何函数中)。


0
投票

这些

extern struct termios cookedInput, rawInput;

是结构termios类型的两个对象的前向声明,但不是它们的定义。

您必须在某些模块中定义对象。

例如,您可以使用main在模块中定义。

struct termios cookedInput, rawInput;

如果您不为对象明确指定初始化器,则它们将像这样初始化

struct termios cookedInput = { 0 }, rawInput = { 0 };
© www.soinside.com 2019 - 2024. All rights reserved.