How to declare my very own CGRectZero like constant?
The other answers are fine -in some cases-.
A) declaring it static
will emit a copy per translation. That is fine if it is visible to exactly one translation (i.e. its definition is in your .m/.c file). Otherwise, you end up with copies in every translation which includes/imports the header with the static definition. This can result in an inflated binary, as well as an increase to your build times.
B) const CGRect CGRectOne = {...};
will emit a symbol in the scope it is declared. if that happens to be a header visible to multiple translations you'll end up with link errors (because CGRectOne
is defined multiple times -- e.g. once per .c/.m file which directly or indirectly includes the header where the constant is defined).
Now that you know the context to use those 2 declarations in, let cover the extern
way. The extern
way allows you to:
- declare the constant in a header
- use the constant in many translations
- while emitting exactly one definition of the constant
The extern
approach is ideal for reusing the constant among multiple files. Here's an example:
File.h
// the declaration in the header:extern const CGRect CGRectOne;
File.c/m
// the definition:#import "File.h"const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };
Note: Omitting the const
would just make it a global variable.
There are a couple of options. With C89,
const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };
With C99,
const CGRect CGRectOne = { .origin.x = 0.0f, .origin.y = 0.0f, .size.width = 1.0f, .size.height = 1.0f};
or
const CGRect CGRectOne = { .origin = { .x = 0.0f, .y = 0.0f }, .size = { .width = 1.0f, .height = 1.0f }};
Something like this
static CGRect CGRectOne = (CGRect){.origin.x = 1.0f, .origin.y = 1.0f, .size.width = 1.0f, .size.height = 1.0f};