在目标C中访问给出链接器错误的全局变量 [英] Accesing global variable giving linker error in objective C
问题描述
我已经声明了一个全局变量,如下所示:
extern NSString * name;
@interface viewcontrollerOne {}
在实现文件中,我使用某种方法访问全局变量像
- (void)someMethod
{
name = @hello;
}
但是这给了链接器错误。
name,引用自:
- viewcontrollerOne.o中的[viewcontrollerOne someMethod]
ld:符号(s)找不到架构i386
clang:error:linker命令失败,退出代码1(使用-v查看调用)
以下仅仅是一个声明:
extern NSString * const name; //<<注意:这通常应该是const
它声明有一个符号 NSString *
命名为 name
。它不会创建存储。
为此,您需要为 name
提供一个定义。为此,请将以下添加到.m 文件中:
NSString * const name = @ 你好;
如果您想在实例方法中设置它,如你的例子所示,那么你可以声明它:
MONFile.h
extern NSString * name;
定义它:
MONFile.m
NSString * name = 0;
然后你可以写 name = @hello;
在你的实例方法中。
I have declared a global variable like below
extern NSString *name;
@interface viewcontrollerOne{}
in implementation file i am accessing that global variable in some method like
-(void)someMethod
{
name = @"hello";
}
but this is giving linker error.
"name", referenced from: -[viewcontrollerOne someMethod] in viewcontrollerOne.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)
The following is merely a declaration:
extern NSString * const name; // << side note: this should typically be const
It declares there is a symbol of NSString*
named name
. It does not create storage.
To do that, you will need to provide a definition for name
. To do this, add the following to your .m file:
NSString * const name = @"hello";
If you want to set it in an instance method, as seen in your example, then you can declare it:
MONFile.h
extern NSString * name;
Define it:
MONFile.m
NSString * name = 0;
then you can write name = @"hello";
in your instance method.
这篇关于在目标C中访问给出链接器错误的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!