Use constants in objective-c. Repeated symbol problems

I have two classes with constants.

For example, there is a class named class_a.m that contains a constant kWidth = 150

,

Also I have a class called class_b.m that contains a constantkWidth = 200

After starting my project, I get a duplicate symbol error, but these files are not nested (I mean class_a in class_b or class_b in class_a). Also I use this constant for implementation only.

Source:

const int kWidht = 150;

      

Error description:

ld: duplicate symbol _kWidht...

      

Thanks for the help!

+3


source to share


2 answers


If a constant is only used in this single implementation file, you must prefix your declaration static

. That is, turn this:

const int kWidth = 150;

      

in it:



static const int kWidth = 150;

      

The keyword static

tells the compiler that this symbol is used only in the current file. 1Without it, the compiler assumes that you are declaring a global variable that can be accessed from anywhere in the final application. Declaring two globals with the same name is not a good idea, as you wouldn't be able to distinguish between them, which is why the compiler is complaining correctly. Fortunately, this is easy to fix, just more detail about your intent with a keyword static

.


1: More precisely "translation unit", but "file" is good enough for the purposes of this question.
+14


source


Another way to work around this situation is to "collect" all the constants in the class. This way you have a better overview of all constant names. The disadvantage is that they can be considered global variables, which is not always evaluated.



+1


source







All Articles