Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linker error on same named constants in different scopes

I have a constant named "ID_KEY" that is declared at the top of 3 separate .m files, neither of which include the other files.

The declaration is as follows:

#import "PublicGamesResponse.h"

NSString *const ID_KEY = @"id";
...
@implementation PublicGamesResponse

And similarly for the two other classes. However I am getting a linker error complaining about multiple definitions of the same name(If I was to comment out two of the definitions, this goes away).

My question is why on earth is the linker complaining about this? Each definition of ID_KEY is outside of the scope of all of the others, so I don't see why the linker is complaining.

As a disclaimer, I cleaned the project and restarted xCode, and looked for similar questions on the site, but had no luck.

like image 759
Brent Hronik Avatar asked Mar 03 '13 19:03

Brent Hronik


1 Answers

When you define variables or constants outside a function, they are placed in the global scope. Linker resolves global references, and it complains when it finds the same name more than once.

To give the constants a scope of their compilation unit (i.e. the file where they are defined) add static in front of their definitions:

static NSString *const ID_KEY = @"id";

This way all functions and methods inside the same file will have access to ID_KEY, but the name would remain in the scope of the file. Essentially, static "hides" the the name from the linker.

like image 175
Sergey Kalinichenko Avatar answered Oct 13 '22 01:10

Sergey Kalinichenko