将 NSString* 数组声明为全局 extern 时,Xcode 中出现错误和警告
我在类的头文件中声明一个 NSString* 数组。
PolygonShape.h
NSString* POLYGON_NAMES[] = {@"Invalid Polygon", @"Monogon", ...};
现在我在 PolyginShape.m 中使用它,如下所示:
- (NSString*) name {
return (POLYGON_NAMES [self.numberOfSides]);
}
numberOfSides 是一个 iVar,它将指示存储多边形名称的索引
到目前为止一切顺利...编译没有任何错误
然后我在实现 main 方法的文件中添加了 PolygonShape.h (注意:这些没有任何类定义和调用函数 C 风格而不是 obj-c 风格)
#import "PolygonShape.h"
现在,当我编译时,我得到构建(链接)错误
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
所以我浏览了堆栈溢出和其他论坛,主要的建议是使全局变量为 extern,所以我做了......
extern NSString* POLYGON_NAMES[] = {@"Invalid Polygon", @"Monogon" .. };
但是我仍然收到链接错误,并且现在还收到 2 个警告,上面
warning: 'POLYGON_NAMES' initialized and declared 'extern'
写着我导入 PolygonShape.h 的两个地方
我在这里缺少什么?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在头文件中将数组声明为:
在源文件中,定义数组并初始化内容:
In your header file declare the array as:
In your source file, define the array and initialize the contents: