外部无类型
如果 extern
的语法是
extern <type> <name>;
如果我有一个未命名的一次性结构,我该如何extern
:
struct {
char **plymouthThemes;
char *plymouthTheme;
} global;
我已经尝试
extern global;
过没有任何类型,但它不起作用。
或者,我必须命名该结构吗?
If the syntax of extern
is
extern <type> <name>;
how do I extern
if I have an unnamed, single use struct:
struct {
char **plymouthThemes;
char *plymouthTheme;
} global;
I've tried
extern global;
without any type, and it doesn't work.
Or, do I have to name the struct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要命名您的结构并将其放入 .h 文件中,或者在每个使用全局的源文件中手动包含定义。像这样
You need to name your struct and put it in a .h file or included the definition by hand in every source file that uses global. Like this
如果你不想命名一个结构体,有一个通用的方法:
宏 GLOBAL 是有条件定义的,因此它的使用将在除了定义 GLOBAL_HERE 的源之外的所有地方添加一个带有“extern”的定义。当您定义 GLOBAL_HERE 时,变量将变为非外部变量,因此它将分配在此源的输出对象中。
还有一个简短的技巧定义(在分配全局变量的单个 .c 文件中设置):
这会导致预处理器删除 extern(用空字符串替换)。但不要这样做:重新定义标准关键字不好。
If you do not want to name a struct there's common method:
The macro GLOBAL is conditionally defined so its usage will prepend a definition with "extern" everywhere except source where GLOBAL_HERE is defined. When you define GLOBAL_HERE then variable gets non-extern, so it will be allocated in output object of this source.
There's also short trick definition (which set in single .c file where you allocate globals):
which cause preprocessor to remove extern (replace with empty string). But do not do it: redefining standard keywords is bad.
这个想法是,您只需要声明一个变量,但仍然需要在使用它的每个其他文件中定义该变量。该定义包括类型(在您的情况下是标头定义结构 - 因此需要包含)和 extern 关键字,以让编译器知道声明位于不同的文件中。
这是我的示例
ext.h
ext1.c
ext2.c
ext3.c
The idea is that you need to declare only one but still need to define the variable in each other file that uses it. The definition includes both the type (in your case a header define structure - which therefore need include) and the
extern
keyword to let know the compiler the declaration is in a different file.here is my example
ext.h
ext1.c
ext2.c
ext3.c