objective c - How do I properly declare a global variable in a header file? -


i testing code declare global variable in header file, i'm getting linker error: "duplicate symbol"

header file:

// //  globalvaraibleclass.h //  globalvar //   #import <foundation/foundation.h>  int gglobalvar = 0; @interface globalvaraibleclass : nsobject  @end 

class file:

// //  globalvaraibleclass.m //  globalvar //  #import "globalvaraibleclass.h"  @implementation globalvaraibleclass  @end 

main:

// //  main.m //  globalvar //  #import <foundation/foundation.h> #import "globalvaraibleclass.h" int main(int argc, const char * argv[]) {      @autoreleasepool {          extern int gglobalvar;          nslog(@"hello, world! %i", gglobalvar);      }     return 0; } 

where going wrong?

that backwards, extern goes in header, declaration setting value goes in implementation file.

the extern specifies variable declared somewhere else. if declaration in header every time header included there declaration , @ link time there multiple definitions not link.

example:

//  globalvaraibleclass.h         extern int gglobalvar;  //  globalvaraible.m #import "globalvaraibleclass.h" int gglobalvar = 3;  //  main.m #import <foundation/foundation.h> #import "globalvaraibleclass.h" int main(int argc, const char * argv[]) {     @autoreleasepool {          nslog(@"hello, world! %i", gglobalvar);      }     return 0; } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -