简体   繁体   中英

linker command failed with exit code 1 - Xcode

I keep getting this error and I don't know why. I've implemented this method in other applications but for some reason it's not working for this one...

I have the following:

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

And it keeps returning a fail build with a linker error saying "duplicate symbol".

I'm so confused. I even tried adding a global header and importing it into both ViewController and Game, but still I get the linker error?:

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

Would there be an issue with Xcode? I've tried the typical "Clean Build" etc... Or am I doing something really dumb? Thanks.

UPDATE BASED ON molbdnilo's ANSWER

Although it's not how I've implemented it before, it's now working with this implementation:

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

Your HighScore variable gets one definition each time you include/import the file somewhere.
(For the gory details, look up the "translation unit" concept.)

If you really, really want to use a global variable, you need to declare it "extern" in a header:

extern NSInteger HighScore;

and define it in exactly one source file:

NSInteger HighScore;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM