Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#import still gets "duplicate symbol" error

When I compile my iPhone app, xCode gives "duplicate symbol" error for my variables in MyConstants.h

I thought if I used:

#import "MyConstants.h"

it would avoid that?

But I still have the problem.

Added info:

  • The error occurs during "linking". (I'm just using xCode's "Build and Go" button.)

  • I also tried the (unnecessary with #import) #ifndef/def method, too.

    Maybe I should just ask this:

    If you needed to access a constant in EVERY part of ALL your source code files... what would you put in your .h file? What would you use to include that constant in other parts of your code.

    I thought (but I guess it's not) it was simple as:

  • MyConstants.h> int thisIsGlobal = 123;

    (No where am I re-defining thisIsGlobal anywhere in any code.)

    And then just "#import MyConstants.h" at the top of each of my other source files.

  • like image 925
    Susanna Avatar asked May 02 '10 17:05

    Susanna


    1 Answers

    What you can do is put in your header (MyConstants.h):

    extern const int MyConstant;
    extern NSString * const MyStringConstant;
    

    And in a source file, include the header above but define the constants (MyConstants.m):

    const int MyConstant = 123;
    NSString * const MyStringConstant = @"SomeString";
    

    Then, you simply need to include the header in any other source file that uses either of these constants. The header is simply declaring that these constants exist somewhere, so the compiler won't complain, because it's the linker's job to resolve these constant names. The source file that contains your constant definitions gets compiled, and the linker sees that this is where the constants are, and resolves all of the references found in the other source files.

    The problem with declaring and defining a constant in a header (that is not declared as static) is that the compiler treats it as an independent global for each file that includes that header. When the linker tries to link all of your compiled sources together it encounters the global name as many times as you have included MyConstants.h.

    like image 170
    dreamlax Avatar answered Sep 21 '22 10:09

    dreamlax