如何在 C 头文件中正确编写 extern 数组(和双精度数组)的声明?

发布于 2024-09-12 23:59:08 字数 544 浏览 1 评论 0原文

假设我想在程序中共享一个全局数据数组,例如:

int lookup_indexes[] = { -1, 1, 1, -1, 2, 1, 1, -2, 2, 2, -1, 1, 1, 2 };

C 头文件中该数组的正确 extern 声明是什么?

另外,像这样的数组怎么样:

int double_indexes[][5] = { { -1, 1, 1, -1, 1 }, { 2, -2, 2, 1, -1 } };

在我的头文件中我尝试了这个:

extern int lookup_indexes[];
extern int double_indexes[][5];

但这会导致编译器错误:

water.h:5: error: array type has incomplete element type

我无法弄清楚。

谢谢,博达·西多。

Suppose I want to share a global array of data across my program, for example:

int lookup_indexes[] = { -1, 1, 1, -1, 2, 1, 1, -2, 2, 2, -1, 1, 1, 2 };

What is the correct extern declaration for this array in the C header file?

Also what about an array like this:

int double_indexes[][5] = { { -1, 1, 1, -1, 1 }, { 2, -2, 2, 1, -1 } };

In my header file I tried this:

extern int lookup_indexes[];
extern int double_indexes[][5];

But this results in compiler errors:

water.h:5: error: array type has incomplete element type

I can't figure it out.

Thanks, Boda Cydo.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

微凉徒眸意 2024-09-19 23:59:08

链接讨论了用作 extern 的数组和大小的问题以及如何管理它们。

  1. 声明一个伴随变量,包含数组的大小,在定义数组的同一源文件中定义和初始化(使用 sizeof)
  2. 为大小定义一个清单常量,以便可以在定义中一致地使用它外部声明

  3. 在数组的最后一个元素中使用一些标记值(通常为 0、-1 或 NULL),以便代码可以确定结束而无需明确的尺寸指示

This link discusses the problems with arrays and sizes used as extern and how to manage them.

  1. Declare a companion variable, containing the size of the array, defined and initialized (with sizeof) in the same source file where the array is defined
  2. define a manifest constant for the size so that it can be used consistently in the definition and the extern declaration

  3. Use some sentinel value (typically 0, -1, or NULL) in the array's last element, so that code can determine the end without an explicit size indication
亣腦蒛氧 2024-09-19 23:59:08

您发布的代码对我来说看起来不错,并且可以在我的机器上编译(gcc -std=c99 -pedanticgcc -std=c90 -pedantic)。您是否复制粘贴了这些行,或者您是否在实际标题中输入了拼写错误?

可能导致错误的示例拼写错误(纯粹猜测):

extern int double_indexes[][];  /* forgot the 5 */
extern int double_indexes[5][]; /* [] and [5] swapped */

The code you posted looks fine to me and compiles (gcc -std=c99 -pedantic and gcc -std=c90 -pedantic) on my machine. Have you copy-pasted these lines or could you have made a typo in your real header?

Example typos that could cause your error (pure guesswork):

extern int double_indexes[][];  /* forgot the 5 */
extern int double_indexes[5][]; /* [] and [5] swapped */
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文