如何为C头文件中声明的外部结构赋值或修改它



我在头文件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中被调用。

我尝试了以下几种解决方案:链接期间对全局变量的未定义引用和使用extern时对变量的C:未定义引用,但出现了一堆不同的错误。

我附上了一张我的航站楼的照片。WSL-Ubuntu-18.04-屏幕截图

声明一个对象不会导致它存在。你需要真正定义它

struct termios rawInput;

可以选择使用初始值设定项,位于顶层(不在任何函数内部(,正好位于一个.c文件中。

这些

extern struct termios cookedInput, rawInput;

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

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

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

struct termios cookedInput, rawInput;

如果您不为对象明确指定初始化程序,那么它们将像一样初始化

struct termios cookedInput = { 0 }, rawInput = { 0 };