【发布时间】:2011-06-09 01:33:44
【问题描述】:
这是一个新手 C/Objective-C 问题:-)
假设我想要一个 CGRectOne 和一个 CGRectTwo 常量。
我该如何声明?
谢谢, 杰里米
【问题讨论】:
标签: objective-c static struct constants extern
这是一个新手 C/Objective-C 问题:-)
假设我想要一个 CGRectOne 和一个 CGRectTwo 常量。
我该如何声明?
谢谢, 杰里米
【问题讨论】:
标签: objective-c static struct constants extern
其他答案都很好 -在某些情况下-.
A) 声明它static 将在每次翻译时发出一个副本。如果它只对一个翻译可见(即它的定义在您的 .m/.c 文件中),那很好。否则,您最终会在每个翻译中得到副本,其中包含/导入带有静态定义的标题。这可能会导致二进制文件膨胀,并增加构建时间。
B) const CGRect CGRectOne = {...}; 将在它声明的范围内发出一个符号。如果这恰好是多个翻译可见的标题,您最终会出现链接错误(因为CGRectOne 被多次定义——例如,每个 .c/.m 文件直接或间接定义一次包括定义常量的标头)。
既然您知道使用这 2 个声明的上下文,让我们介绍一下 extern 方式。 extern 方式允许您:
extern 方法非常适合在多个文件中重用常量。这是一个例子:
文件.h
// the declaration in the header:
extern const CGRect CGRectOne;
文件.c/m
// the definition:
#import "File.h"
const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };
注意:省略 const 只会使其成为全局变量。
【讨论】:
extern const CGRect SCREENBOUNDS; .. 但它说的是 Type name does not allow storage class to be specified.. 你帮我理解这个错误吗?
@interface (或其他范围)内声明常量。 extern 常量应在与其他 extern C 声明(例如函数、常量)相同的(全局)范围内声明。
这里使用的技术对我来说效果很好:http://www.cocos2d-iphone.org/forum/topic/2612#post-16402
本质上它是 Justin 描述的 extern 方法,但它提供了一个非常完整的示例。
此外,StackOverflow 上的这个答案也提供了一个很好的例子:Constants in Objective-C
【讨论】:
有几个选项。使用 C89,
const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };
使用 C99,
const CGRect CGRectOne = {
.origin.x = 0.0f,
.origin.y = 0.0f,
.size.width = 1.0f,
.size.height = 1.0f
};
或
const CGRect CGRectOne = {
.origin = { .x = 0.0f, .y = 0.0f },
.size = { .width = 1.0f, .height = 1.0f }
};
【讨论】:
类似的东西
static CGRect CGRectOne = (CGRect){.origin.x = 1.0f, .origin.y = 1.0f, .size.width = 1.0f, .size.height = 1.0f};
【讨论】:
-std=c99 打开了 C99 支持,现在它也适用于我。