Objective-C global array ints not working as expected

In my MyConstants.h file ... I have:

int abc[3];

      

In my respective file MyConstants.m ... I have:

extern int abc[3] = {11, 22, 33};

      

In each of my other * .m files ... I have

#import "MyConstants.h"

      

Inside one of my viewDidLoad {} methods, I have:

extern int abc[];
NSLog(@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(int));  

      

Why does it display "abc = (0) (3)" instead of "abc = (22) (3)"?

How do you make this work expected?

+2


a source to share


1 answer


extern

must be in the header declaration, not in the definition in the source file. extern

tells the compiler that the symbol exists somewhere else, it may or may not be in the same translation unit. It is the linker's job to ensure that all declared symbols have actually been defined.

Constant header ( MyConstants.h

):

extern int abc[3];

      

Source of constants ( MyConstants.m

):

int abc[3] = {11, 22, 33};

      



Another source ( SomeFile.m

):

#include "MyConstants.h"
...
- (void) someMethod
{
    NSLog (@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(int));
}

      

Also note that when measuring the size of an array, it is less error prone to divide by the size of the first element, so if the type abc

changes (i.e., from int

to double

), the results remain valid.

- (void) someMethod
{
    NSLog(@"abc = (%d) (%d)", abc[1], sizeof(abc)/sizeof(abc[0]));
}

      

+5


a source







All Articles