2

I'm trying to declare and initialize global C-variables.

const int numberOfTickMarks = 6;
const double tickValues[numberOfTickMarks] = {500, 2000, 3000, 4000, 6000, 8000};

When I do this in my header file (before the @interface), I get a linker error. But when I do this in the .m file (before @implementation), things seem to work as desired.

Is the latter the accepted way to declare global constants for C/Objective-C?

JohnK
  • 6,865
  • 8
  • 49
  • 75
  • 1
    http://stackoverflow.com/questions/4481554/global-variables-in-objective-c-difference-in-extern-and-top-of-m-file-declar?rq=1 – matt May 08 '13 at 18:16
  • The question is whether you want them for just one file or shared over multiple files. You are not going to #import a _.m_ file, so "the latter" (`const double` in the _.m_ file) would not suffice in the second case. – matt May 08 '13 at 18:18

3 Answers3

1

Your global variables should be declared like this in the header file:

extern const int numberOfTickMarks;
extern const double tickValues[numberOfTickMarks];

Without extern, linker errors are inevitable.

In the implementation file, you would have to define them again like this:

const int numberOfTickMarks = 6;
const double tickValues[numberOfTickMarks] = {500, 2000, 3000, 4000, 6000, 8000};
user123
  • 8,970
  • 2
  • 31
  • 52
  • So basically you're saying I just have to add `extern` to the declarations I put in the header file. Of course `numberOfTickMarks` is still undefined there, so can't be used for the length of the array. I'd like to make it so I have to change as little code as possible. Is there any way to allow the `numberOfTickMarks` in the definition of the array? – JohnK May 08 '13 at 18:27
  • (Sorry, got declaration and definition mixed up.) Is there any way for the compiler to get the size of an array? If so, I could use that to *define*/set `numberOfTickMarks`. – JohnK May 08 '13 at 18:38
  • 1
    `sizeof(tickValues)/sizeof(*tickValues)` = size of the array – user123 May 08 '13 at 18:53
1

What I would do in a case where I have a "magic number" is a #define:

#define NUM_TICK_MARKS 6

It can go in the .m file, but if it is to be shared widely, I might put it in the .pch file.

And by the way:

The numberOfTickMarks is not necessary:

const double tickValues[numberOfTickMarks] = {500, 2000, 3000, 4000, 6000, 8000};

The initializer says quite clearly how big the array is!

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Why not define them on the main.m file ?

type myVar;

And declare on the header, use:

extern type myVar;

Edit

By what you wrote on the comments, I think you need to use class variables. Since this resource is not available in objective-c, I see 2 alternatives:

1) Use c++ as in this SO answer

2) Use a shared instance, as described in this answer

Personally, I'd go with number 2

Community
  • 1
  • 1
luksfarris
  • 1,313
  • 19
  • 38