How to declare my very own CGRectZero like constant?

jchatard picture jchatard · Jan 14, 2011 · Viewed 10.9k times · Source

This is a newbie C/Objective-C question :-)

Let say I want a CGRectOne and a CGRectTwo constants.

How can I declare that?

Thanks, Jérémy

Answer

justin picture justin · Jan 14, 2011

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.