0

Possible Duplicate:
Global Variables in Cocoa/Objective-C?
problem with declare a global variable in objective c

I was defining a global variable inside my .h, which other classes were accessing by including the classes ".h" file. This worked fine, from advice I received, I've now moved the variable to the ".m", because I was informed, that otherwise every class that includes the .h will be redeclaring it, is this correct? But now my other files can't access it, and I'm assuming I'm not supposed to include ".m" files.... should I use the #define preprocessor, so that is only defined once? How do i do this?

Community
  • 1
  • 1
williamsandonz
  • 15,864
  • 23
  • 100
  • 186
  • 1
    I [gave you](http://stackoverflow.com/a/11007105/603977) the info you needed originally; declare the same variable with `extern` in the header, and with no qualifier in the .m file. – jscs Jun 13 '12 at 06:24
  • Thanks Josh got it :) Sorry missed that. – williamsandonz Jun 13 '12 at 06:46

3 Answers3

6

You can declare variables in .h files.

globals.h:

extern int myGlob;

You cannot define the variable in a .h, You have to define it in a .c or .m:

globals.m:

int myGlob;

You can import globals.h from any other file that needs to access myGlob:

myApp.m:

#import "globals.h"

main() {
    myGlob++;
}
mouviciel
  • 66,855
  • 13
  • 106
  • 140
2

You can use #define number 123 or #define string @"abc" inside the .h and any file that imports it should be able to use the preprocessor name you chose. k is a common prefix for these types of macros as they're in fact constant values.

NOTE: The comments show that there is a difference between using preprocessors you define and actual global variables (with extern declared) though both can be used in separate files by importing the .h file where you declared/defined them.

erran
  • 1,300
  • 2
  • 15
  • 36
  • Those aren't variables; they're just text substitutions. This answer really doesn't solve the problem that Baconbeastnz has. – jscs Jun 13 '12 at 06:44
  • I never said they were variables, I'll edit my answer to clarify that. The answer does cover the part where he asked if it was appropriate to use a #define statement to define something once across files. – erran Jun 13 '12 at 06:47
  • Your answer says "it should be able to use the _variable_ name". Baconbeastnz is asking about a global variable that has appeared in a couple ([1](http://stackoverflow.com/questions/11008816/), [2](http://stackoverflow.com/questions/11007057/)) of questions today. – jscs Jun 13 '12 at 07:03
  • Changing my answer according to the question, and clarifications I find necessary. I'll skim the other questions and decide if I can better answer this question but the #define methods is a valid way to do what @Baconbeastnz was asking about in part of this specific question. – erran Jun 13 '12 at 07:06
-1

static variables are declared only once

Michał Kreft
  • 548
  • 3
  • 16