0

Possible Duplicate:
obj-c duplicate symbol for header variable

I have multiple .m and .mm files in my project. I can include this .h file (that dosent have a corresponding .m or .mm file) in as many .m files as I like but when I include it in more than one .mm file I get the duplicate symbols linker error.

Also in the .h file I have surrounded the content with preprocessor commands (Are these respected in obj-c?) here is what it mostly looks like:

#ifndef _CONFIG_H_
#define _CONGIF_H_

CGFloat WIDTH, HEIGHT;
// other similar code...

#endif

I get the duplicate symbols error on WIDTH and HEIGHT

Community
  • 1
  • 1
richy
  • 2,716
  • 1
  • 33
  • 42
  • 1
    Header file variables are declared "extern" (as in `extern CGFloat WIDTH, HEIGHT;`) and in a **SINGLE** .c/.mm file declared *without* "extern" (what you have above). This tells the compiler that anyone including your header knows these symbols exist, and at link-time those references are fixed up to the globals you declared in the .c/.mm file. This is (i believe) the second-most-frequent C/C++ question asked on SO (templates in .cpp files being #1 I'm pretty sure) but for the life of me I can't nail down a solid duplicate example right now. Sorry about that. – WhozCraig Nov 10 '12 at 04:42
  • 1
    possible duplicate of [obj-c duplicate symbol for header variable](http://stackoverflow.com/questions/1908222/obj-c-duplicate-symbol-for-header-variable) **and also** [Struct with a value in a header file causing duplicate symbol linker error](http://stackoverflow.com/questions/2206853/struct-with-a-value-in-a-header-file-causing-duplicate-symbol-linker-error) –  Nov 10 '12 at 06:11

1 Answers1

7

You should add

extern

keyword before CGFloat declaration in the header, and define the variables without extern in the .m file to avoid defining your variables in multiple places.

In the header:

extern CGFloat WIDTH, HEIGHT;

In a .m file (one of them, any one)

CGFloat WIDTH, HEIGHT;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @WhozCraig It's quite an abvious error, if you thinj about it a bit. `int var;` **defines** the variable, not only declares it. That's just the fault of functions that they can be declared without `extern` to actually be edtern. –  Nov 10 '12 at 05:40
  • @H2CO3 I *know* the error (see the comments under the OP). I was looking for a *duplicate* to reference and close this out, but I couldn't find a solid example, which shocks me considering how often this question is asked. – WhozCraig Nov 10 '12 at 06:08
  • @WhozCraig Then you missed something... See my comment. –  Nov 10 '12 at 06:10
  • @H2CO3 That was *exactly* what I was looking for. Clearly I had way too wide a search pattern. thanks for the samples. – WhozCraig Nov 10 '12 at 06:37
  • @WhozCraig Then why not vote for closure in this case? ;P –  Nov 10 '12 at 06:39