0

I need some globals in my Objective-C application. For that purpose, I've created class Globals (that inherits NSObject) and put readonly properties in it. I've also declared some constants, like this:

imports, etc.
.
.
.
#ifndef GLOBALS_H
#define GLOBALS_H

const int DIFFICULTY_CUSTOM = -1;
const int other_constants ...
#endif
.
.
.
interface, etc.

But when I try to compile it, I get linker error: "Duplicate symbol DIFFICULTY_CUSTOM". Why is that happening, should ifndef prefent it?

xx77aBs
  • 4,678
  • 9
  • 53
  • 77
  • possible duplicate of [Where do you declare constant in objective c?](http://stackoverflow.com/questions/6188672/where-do-you-declare-constant-in-objective-c) – mmmmmm Jul 12 '12 at 14:04

2 Answers2

3

The issue is that const int DIFFICULTY_CUSTOM = -1; allocates a int of that name is in every object file you include the header for.
You should only have the declaration extern const int DIFFICULTY_CUSTOM; in each header. The actual value should then be defined const int DIFFICULTY_CUSTOM = -1; in one object file ( ie .m or .c ).

In this case I would just use #define to set the value.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
1

Here's how I'd do it:

In constants.m:

const int DIFFICULTY_CUSTOM = -1;

In constants.h:

extern const int DIFFICULTY_CUSTOM;

and in the .pch file:

#import "constants.h"
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160