Linker error on identical named constants in different areas

I have a constant named "ID_KEY" which is declared at the top of three separate .m files, none of which contain other files.

The ad is as follows:

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

And similarly for the other two classes. However, I get a linker error complaining about multiple definitions with the same name (if I were to comment on two definitions, this will disappear).

My question is, why is the agent really complaining about this? Each definition of ID_KEY goes beyond everyone else, so I don’t understand why the linker complains.

As a disclaimer, I cleaned up the project and restarted xCode and looked at similar issues on the site, but no luck.

+6
source share
1 answer

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

To provide constants with the scope of their compilation unit (i.e. the file where they are defined), add static before your definitions:

 static NSString *const ID_KEY = @"id"; 

Thus, all functions and methods inside the same file will have access to ID_KEY , but the name will remain in the file area. Essentially, static "hides" the name from the linker.

+12
source

All Articles