链接器命令失败,退出代码1 - Xcode

linker command failed with exit code 1 - Xcode

本文关键字:代码 Xcode 退出 命令 失败 链接      更新时间:2023-10-16

我一直得到这个错误,我不知道为什么。我已经在其他应用程序中实现了这个方法,但由于某种原因,它不适合这个…

我有以下内容:

ViewController.h:

    NSInteger HighScore;

ViewController.m:

 - (void)viewDidLoad {
      ...
      //load highscores
      HighScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];
      HighscoreLabel.text = [NSString stringWithFormat:@"%li", (long)HighScore];
 }

Game.m:

 #import "ViewController.h"
 ...
 //set/save new highscore
 if(Score > HighScore){
    [[NSUserDefaults standardUserDefaults] setInteger:Score forKey:@"HighScoreSaved"];
 }

它一直返回一个失败的构建,链接器错误说"重复符号"。

我很困惑。我甚至尝试添加一个全局标题,并将其导入ViewController和Game,但我仍然得到链接器错误?:

Global.h:

 #ifndef _Global_h
 #define _Global_h
 NSInteger HighScore;
 #endif

ViewController.m:

 #import "Global.h"
 - (void)viewDidLoad {
      ...
      //load highscores
      HighScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];
      HighscoreLabel.text = [NSString stringWithFormat:@"%li", (long)HighScore];
 }

Game.m:

 #import "Global.h"
 ...
 //set/save new highscore
 if(Score > HighScore){
    [[NSUserDefaults standardUserDefaults] setInteger:Score forKey:@"HighScoreSaved"];
 }

Xcode会有问题吗?我尝试过典型的"干净构建"等等……还是我做了什么蠢事?谢谢。

基于molbdnilo的答案的UPDATE

虽然这不是我以前实现它的方式,但它现在与这个实现一起工作:

ViewController.h:

 extern NSInteger HighScore;

ViewController.m:

 //load highscore
 HighScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];
 HighscoreLabel.text = [NSString stringWithFormat:@"%li", (long) HighScore];

Game.h:

 NSInteger HighScore; //exactly as declared in ViewController.h

Game.m:

 //if higher score, overwrite
 if (Score > HighScore){
     [[NSUserDefaults standardUserDefaults] setInteger:Score forKey:@"HighScoreSaved"];
 } 

每次在某处包含/导入文件时,您的HighScore变量获得一个定义。
(有关血腥的细节,请查阅"翻译单位"概念。)

如果你真的,真的想使用一个全局变量,你需要声明它"extern"在头文件中:

extern NSInteger HighScore;

一个源文件中定义:

NSInteger HighScore;