views:

1292

answers:

1

I am declaring an array of NSString* in a header file of a class.
PolygonShape.h

NSString* POLYGON_NAMES[] = {@"Invalid Polygon", @"Monogon", ...};

Now I am using this in PolyginShape.m as follows:

- (NSString*) name {
return (POLYGON_NAMES [self.numberOfSides]);
}

numberOfSides is an iVar which will indicate the index at which the polygon name is stored
So far so good ... it was compiling without any errors

Then I added PolygonShape.h in my file that implements main method (note: these does not have any class definition and call functions C-Style rather than obj-c Style)

#import "PolygonShape.h"

Now when I compile, I am getting a build (linking) error

ld: duplicate symbol _POLYGON_NAMES in /Users/../Projects/CS193P/1B/What_A_Tool/build/What_A_Tool.build/Debug/What_A_Tool.build/Objects-normal/i386/PolygonShape.o and /Users/../Projects/CS193P/1B/What_A_Tool/build/What_A_Tool.build/Debug/What_A_Tool.build/Objects-normal/i386/What_A_Tool.o
collect2: ld returned 1 exit status

So I went thru stack overflow and other forums and mostly the advice was to make the global variable extern and so I did ...

extern NSString* POLYGON_NAMES[] = {@"Invalid Polygon", @"Monogon" .. };

However I am still getting the linking error and also getting 2 warnings now that says

warning: 'POLYGON_NAMES' initialized and declared 'extern'

at both the places where i am importing PolygonShape.h

What am I missing here?

Thanks.

+4  A: 

In your header file declare the array as:

extern const NSString* POLYGON_NAMES[];

In your source file, define the array and initialize the contents:

const NSString* POLYGON_NAMES[] = {@"Invalid Polygon", @"Monogon" };
dmercredi
Well in that case wont the "user" of the class be unaware of what the array POLYGON_NAMES[] is holding just by looking at the header? This is supposed to be a class-level (static in Java/C++ terms) variable, so should'nt it be available to the user in the header file itself?
Dev
There is no way to declare the array with its contents in the header file in C/C++/Objective C. dmercredi is correct, you need to declare the existance (with extern) of the array in the header file, and the actual array in the implementation. Otherwise the array would be declared once for each time the header is included (hence the original duplicate declaration error you suffered). Saying "extern" means you are declaring, but not defining, the array, so it makes no sense to also initialize it, hence the warnings you suffered in your second attempt.
Peter N Lewis
Thanks dmercredi and Peter
Dev