objective-clinker

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?


Solution

  • 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.