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

时间:2015-06-02 13:54:39

标签: c++ ios xcode linker

我一直收到这个错误,但我不知道为什么。我已经在其他应用程序中实现了这种方法,但出于某种原因,它不能用于此方法...

我有以下内容:

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会出现问题吗?我尝试过典型的" Clean Build"等等... 或者我做的事情真的很蠢?感谢。

更新基于molbdnilo的答案

虽然我之前没有实现它,但它现在正在使用此实现:

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"];
 } 

1 个答案:

答案 0 :(得分:1)

每次在某处包含/导入文件时,HighScore变量都会得到一个定义 (有关血淋淋的细节,请查看“翻译单元”概念。)

如果您确实想要使用全局变量,则需要在标题中声明它“extern”:

extern NSInteger HighScore;

一个源文件中定义

NSInteger HighScore;