obj-c duplicate symbol for header variable

白昼怎懂夜的黑 提交于 2019-12-18 03:47:04

问题


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?


回答1:


#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 ;)




回答2:


#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




回答3:


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'. :)



来源:https://stackoverflow.com/questions/1908222/obj-c-duplicate-symbol-for-header-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!