Objective-C 全局整数数组未按预期工作

发布于 2024-09-01 16:43:27 字数 471 浏览 1 评论 0原文

在我的 MyConstants.h 文件中...我有:

int abc[3];

在我的匹配 MyConstants.m 文件中...我有:

extern int abc[3] = {11, 22, 33};

在我的每个其他 *.m 文件中...我有

#import "MyConstants.h"

Inside 1 of my viewDidLoad{} 方法,我有:

extern int abc[];
NSLog(@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(int));  

为什么显示“abc = (0) (3)”而不是“abc = (22) (3)”?

我如何使这项工作按预期进行?

In my MyConstants.h file... I have:

int abc[3];

In my matching MyConstants.m file... I have:

extern int abc[3] = {11, 22, 33};

In each of my other *.m files... I have

#import "MyConstants.h"

Inside 1 of my viewDidLoad{} methods, I have:

extern int abc[];
NSLog(@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(int));  

Why does it display "abc = (0) (3)" instead of "abc = (22) (3)"?

How do I make this work as expected?

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

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

发布评论

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

评论(1

傲性难收 2024-09-08 16:43:27

extern 需要位于标头的声明中,而不是源文件的定义中。 extern 告诉编译器该符号存在于其他地方,它可能位于也可能不在同一个翻译单元中。链接器的工作是确保所有声明的符号都已实际定义。

常量标头 (MyConstants.h):

extern int abc[3];

常量源 (MyConstants.m):

int abc[3] = {11, 22, 33};

其他源 (SomeFile.m):

#include "MyConstants.h"
...
- (void) someMethod
{
    NSLog (@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(int));
}

另外,请注意,当测量数组的大小时,除以第一个元素的大小更不容易出错,因此如果 abc 的类型发生变化(即从 int 变为double),结果仍然有效。

- (void) someMethod
{
    NSLog(@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(abc[0]));
}

The extern needs to be in the declaration in the header, not in the definition in the source file. extern tells the compiler that the symbol exists somewhere else, it may or may not be in the same translation unit. It is the linker's job to make sure that all declared symbols were actually defined.

Constants Header (MyConstants.h):

extern int abc[3];

Constants Source (MyConstants.m):

int abc[3] = {11, 22, 33};

Other Source (SomeFile.m):

#include "MyConstants.h"
...
- (void) someMethod
{
    NSLog (@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(int));
}

Also, note that when measuring the size of an array, it is less error-prone to divide by the size of the first element, so that if the type of abc changes (i.e. from int to double), the results are still valid.

- (void) someMethod
{
    NSLog(@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(abc[0]));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文