像这样在 C 中使用 extern 有什么问题吗?
我已经搜索过一些关于这个的东西,但我仍然不明白它..
file1.h
extern int *game_array[5];
Player.c
#include "file1.h"
void *delete_player(player_struct *player)
{
... //some code
game_array[5] = 5; //undefined reference to `game_array`
... //some code
}
当我不使用 extern 时,它“工作正常”=我可以毫无错误地构建它,但程序不是完成的 .. 我想使用 extern 没问题,但出了点问题.. 我想使用我的所有 .c 源文件中的 game_array ...服务器上的游戏数组,我的应用程序中只有该数组的一个实例。
I've already searched something abou this but I've still don't understand it..
file1.h
extern int *game_array[5];
Player.c
#include "file1.h"
void *delete_player(player_struct *player)
{
... //some code
game_array[5] = 5; //undefined reference to `game_array`
... //some code
}
When I don't use extern it "work's fine" = I can build it withou errors, but the program's not finished ..
I suppose the using extern is fine but something is wrong ..
I want to use this game_array ... array of games on server from all my .c source files, there's only one instance of this array in my aplication.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在
.c
文件之一中定义game_array
,并将该文件编译/链接到可执行文件中。定义将如下所示:
您的
file1.h
所说的基本上是“我的项目中某处存在一个名为game_array
的变量,并且它具有这样的内容 -以及这样的类型”。但是,该变量实际上并不存在,除非您在某处(通常是在.c
文件中)定义了它。You need to define
game_array
in one of your.c
files, and compile/link that file into your executable.The definition will look like this:
What your
file1.h
is saying is basically "There exists a variable calledgame_array
somewhere in my project, and it has such-and-such type". However, the variable doesn't actually exist until you've defined it somewhere (typically, in a.c
file).extern
关键字基本上意味着编译器不应该抱怨该符号,即使它没有定义,因为它在链接时可用。因此,如果它没有在链接时定义,显然会出现错误。
您需要在您的 C 文件之一中提供一个实现:
类似于:
The
extern
keyword basically means that the compiler should not complain about the symbol, even if it's not defined, because it will be available at link-time.So if it's not defined at link-time, you'll obviously have errors.
You need to provide an implementation in one of your C file:
Something like:
编写
extern int *game_array[5];
意味着在某个文件中的某个地方,有一个game-array
的实际定义 - 即没有的声明extern。
您未能提供该信息,因此链接器会抱怨实际变量在任何地方都不存在。Writing
extern int *game_array[5];
means that somewhere, in some file, there's an actual definition forgame-array
-- i.e., a declaration without theextern.
You're failing to provide that, so the linker complains that the actual variable doesn't exist anywhere.