Objective-C 全局整数数组未按预期工作
在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
extern
需要位于标头的声明中,而不是源文件的定义中。extern
告诉编译器该符号存在于其他地方,它可能位于也可能不在同一个翻译单元中。链接器的工作是确保所有声明的符号都已实际定义。常量标头 (
MyConstants.h
):常量源 (
MyConstants.m
):其他源 (
SomeFile.m
):另外,请注意,当测量数组的大小时,除以第一个元素的大小更不容易出错,因此如果
abc
的类型发生变化(即从int
变为double
),结果仍然有效。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
):Constants Source (
MyConstants.m
):Other Source (
SomeFile.m
):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. fromint
todouble
), the results are still valid.