xx77aBs
xx77aBs

Reputation: 4778

Duplicate symbol error in objective-c

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?

Upvotes: 0

Views: 391

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53231

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"

Upvotes: 1

mmmmmm
mmmmmm

Reputation: 32720

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.

Upvotes: 3

Related Questions