Question

It was my impression that using #import would only import a file once per build, yet after trying to define a variable in a header, and then importing that header in two different source files, I get a duplicate symbol linker error for the variable. How is this possible?

Was it helpful?

Solution

#import makes header to be included once per file, but not per build. So your variable is defined in every file where you import your header and as global variable is visible by default in whole project you get linker error.
Correct way to define a global variable (if it is what you want to do) is define it in implementation file and reference it with the key word external in other files.
Also defining variable in header as static will limit its visibility to the single file, so you will get no error, but likely not the result you want ;)

OTHER TIPS

#import makes sure the 'declarations' are included only once. Since you are defining a variable which is a 'definition' which make you get a duplicate symbol linker error.

To solve this error - use .h for only declaration and .m for definition

As Vladimir explained you can use extern

I had a bunch of duplicate symbols suddenly appear after I had set up a new class.

Finally realized I'd managed to do this in the .m file:

#import "other-file.m"

Note the 'm'. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top