I’m getting the linker command failed with exit code 1 (use -v to see invocation) error when attempting to instantiate a singleton.
Here is the code I’ve been using to make my class a singleton:
.h
@interface CoursesManager : NSObject
{
}
+ (id)SharedInstance;
@end
.m
@implementation CoursesManager
+ (id)SharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
@end
And this is how I’ve been using it in other classes:
coursesManager = [CoursesManager SharedInstance];
After looking a little more into it, it seems that simply importing this file in other .m’s causes the linker error. I’m pretty confused as to what could be causing this. Any help would be appreciated.
Just for reference, I’m using Xcode 4.3.3.
EDIT full comments of the error are as follows:
ld: duplicate symbol _MAX_COURSES in ../Objects-normal/armv7/CourseEditorViewController.o and …/Objects-normal/armv7/CourseSelectionViewController.o for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Above @interface CoursesManager, I’ve declared two const int variables, MAX_COURSES and MAX_HOLES.
Do you have
@endat the end of your implementation inCourseManager.m?Are you importing any files in your
CourseManager.hfile? If so, make sure none of the files you are importing have an import statement forCourseManager.hin them (i.e. two files importing each other).FYI, This is the recommended and thread-safe way to create a singleton:
Update
The error came because @rkeller was declaring
const intvalues in his CourseManager.h file and then importing that .h file into a few other files.To avoid this, there are a few things you can do:
const intto#defineconst inttostatic const intCourseManager.hasextern const int MyConstantand then instantiate the value inCourseManager.mlike so:const int MyConstant = 0;When you declare a non-static constant in the header file, the compiler treats that constant as an independent global for each file that imports that header file. Then, when the linker tries to link all of the compiled sources, it will encounter the global numerous times — hence the linker error.