Duplicate symbol error — global constant

2019-02-12 00:02发布

问题:

In the header of the class, outside of interface declaration, I've declared global constants:

NSString * const gotFilePathNotification = @"gotFilePath";
NSString * const gotResultNotification = @"gotResultOfType";

gotResultNotification is used only in this class (yet), but I reference gotFilePathNotificaion in another class implementation. To do it, I import this header.

When I try to compile, I get a duplicate symbol linker error about gotFilePathNotification in this header. Why does it happen?

回答1:

You have two identifier(s) with same name across two different compilation unit(s) at file scope. This violates One Definition Rule. Instead you need to -

  1. Declare the global variables marking to have external linkage in a header file.

    extern NSString * const gotFilePathNotification;
    
  2. Now provide the definition in only one source file.

    NSString * const gotFilePathNotification = @"gotFilePath";
    

Now where ever you need to use these variables, include the header in the source file.



回答2:

You need to declare them extern in the header file and define them in implementation file. See this question for clarification. Global Variables in Cocoa/Objective-C? .

The second response provides the clarification that I will reiterate here. The default storage qualifier for variables is static. This means when you try to link two different files with the same variable, as will happen when you import your header file, the linker will construe that the variable is multiply-defined.



回答3:

Also make sure you're including the h file and not the m file. This was driving me nuts.