【发布时间】:2021-01-21 17:54:16
【问题描述】:
我正在尝试从另一个 c 文件访问一个 c 文件中定义的结构。问题是 我不能使用 extern 关键字 我也不能在头文件中定义结构。如何访问abstract.c 内use_abstract.c 中定义的结构?这是一个最低限度的可生产示例:
抽象.c
#include <stdio.h>
#include <stdlib.h>
typedef struct s_strukt {
int x;
} strukt;
strukt* create_struct() {
strukt* s = malloc(sizeof(strukt));
return s;
}
抽象.h
#ifndef H_ABSTRACT
#define H_ABSTRACT
struct s_strukt;
#endif
use_abstract.c
#include <stdio.h>
#include "abstract.h"
int main() {
strukt *s = create_struct();
s->x = 0;
return 0;
}
执行以下会导致错误gcc use_abstract.c abstract.c:
use_abstract.c:6:5: error: use of undeclared identifier 'strukt'; did you mean 'struct'?
strukt *s = create_struct();
^~~~~~
struct
use_abstract.c:6:5: error: declaration of anonymous struct must be a definition
use_abstract.c:6:5: warning: declaration does not declare anything [-Wmissing-declarations]
use_abstract.c:7:5: error: use of undeclared identifier 's'
s->x = 0;
^
1 warning and 3 errors generated.
【问题讨论】:
-
为什么不能使用
extern关键字? -
这只是一个标准。我正在尝试解决我的编程书中的一个问题,以自学 C 编程。但是我不相信上述方法会起作用,这就是我要问的原因。
-
extern关键字在这里不相关。它不适用于类型。此外,它是在文件范围内声明的函数和对象的默认值。显式声明文件范围 variableextern确实是有目的的,但在呈现的代码中没有这样的变量。 -
@pointersarehard "尝试解决我的编程书中的问题" 任何(严肃的)编程书练习都不太可能要求您使用未知且无法访问的结构。这闻起来像 XY problem,如果你说出你要解决的实际问题会更好,因为这可能不是正确的解决方案。
-
@mkrieger1 我能以任何方式改进这个问题吗?我无法提出更多问题,因为这篇文章有 0 票。
标签: c abstract-class abstract-data-type