Quick tip: Global #defines

Some times, there is a need to have a function available in multiple classes. Oftentimes, projects with multiple classes have #defines scattered all over the place.

What I’ve started to do is create a file named global.h (New File, select “C and C++” under Mac OS X, and then select “Header File”).

Then, in order to have it be automatically referenced throughout the project, I add it to the prefix header file (called something like YourProjectName_Prefix.pch):

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "global.h"

I also start by putting the following functions in the globals.h file (I typically need them for any project I’m working on):

#pragma mark -
#pragma mark Global Functions

#define degreesToRadian(x)				(M_PI * (x) / 180.0)
#define RGB(r, g, b)					[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a)				[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

After that, I put any of my defined variables (widths and heights, index offsets, etc.

And after that, I create my notification strings, similar to:

#pragma mark -
#pragma mark Notification Strings

#define PPSubpanelClose		@"PPSubpanelClose"

(Typically in the form “2 initials for project” + noun/class-name + verb)

And finally, I put any enums, similar to:

enum btnSelectionPositions {

This technique has proven very useful when working on projects with other developers — we all know where everything is, and we are guaranteed that any new classes we create will automatically be able to reference these values.

(We have also used it for creating debugging flags and OS flags, for compiler directives to enable/disable functionality when testing and demoing…)

There are, of course, ways that this can be abused, but I hope people will use this for the forces of good. It can definitely help in the organization of larger projects (especially when developing for the iPad with dozens upon dozens of classes and subclasses, and many different notifications being sent back and forth between them).


About jeffrey

Jeffrey Berthiaume is a multimedia developer and internet architect who has designed and built award-winning websites, kiosks, and content management systems. He bridges the gap between creative and technology with an ability to balance the needs of designers and marketing with the capabilities of existing technology.
This entry was posted in Development, iOS, Tutorials. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>