This question already has answers here:
Accesing global variable giving linker error in objective C
                            
                                (2个答案)
                            
                    
                6年前关闭。
        

    

我正在制作一个小型,简单的应用程序,因此我决定在Singletons上使用全局变量。我也只用一个。

我的应用程序从一个小的首选项文件中提取一个int,并将其作为NSInteger设置为全局变量。应用程序运行时,可能会更改全局变量。

AppController.h

#import <Cocoa/Cocoa.h>

extern NSInteger preferenceNumber;

@interface ....


应用控制器

-(void)someMethod {
    ...
    //fileContents is a string containing the int that is inside the file
    preferenceNumber = [fileContents intValue]
    ...
}


链接器错误(2):
 架构x86_64的未定义符号:
  “ _preferenceNumber”,引用自:
      -[AppController.o中的[AppController someMethod1]
      -AppController.o中的[AppController someMethod2:]
ld:找不到架构x86_64的符号
clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

粗体部分是两个错误。

是什么原因造成的?解决问题的最简单,最佳方法是什么?

最佳答案

只需在实现类中添加一行:

AppContollr.m


@implementation AppContoller
NSInteger preferenceNumber;

关于objective-c - 全局变量的链接器错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19237342/

10-10 14:47