Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants in Objective-C and "duplicate symbol" linker error

I've declared a constant with the same name in some different classes, in their .m file, this way:

@implementation MyViewController
const NSInteger numberOfItems = 6;
...
@end

But I get a "duplicate symbol" error when trying to build the project. I've found several posts dealing with this issue regarding extern or global constants, but what I'd want is just declaring some constants private to their class, how can I do that?

Thanks

like image 896
AppsDev Avatar asked Jun 17 '13 10:06

AppsDev


People also ask

How linkers resolve global symbols defined at multiple places?

- GeeksforGeeks How Linkers Resolve Global Symbols Defined at Multiple Places? At compile time, the compiler exports each global symbol to the assembler as either strong or weak, and the assembler encodes this information implicitly in the symbol table of the relocatable object file. Functions and initialized global variables get strong symbols.

Why does the linker generate an error message when using strong symbols?

In this case, the linker will generate an error message because the strong symbol main is defined multiple times ( rule 1 ): $ gcc foo1.c bar1.c /tmp/cca015022.o: In function ‘main’: /tmp/cca015022.o (.text+0x0): multiple definition of ‘main’ /tmp/cca015021.o (.text+0x0): first defined here

What are strong and weak symbols in C++?

Functions and initialized global variables get strong symbols. Uninitialized global variables get weak symbols. For the following example programs, buf, bufp0, main, and swap are strong symbols; bufp1 is a weak symbol.

Can the linker detect multiple definitions of X?

Notice that the linker normally gives no indication that it has detected multiple definitions of x. The same thing can happen if there are two weak definitions of x ( rule 3 ):


1 Answers

If you want to use constant only in one .m file then declare it as static. For example:static NSString * const CONSTANT_STRING = @"Constant I am".

In case of NSInteger you can write in your every .m file:

static const NSInteger my_const = 3;

If you want globals (one constant with one value visible in every file) then write in your .h:

extern const NSInteger my_global_const;

and in your .m file you can add

const NSInteger my_global_const = 5;
like image 85
MichK Avatar answered Oct 25 '22 01:10

MichK