标头变量的obj-c重复符号 [英] obj-c duplicate symbol for header variable

查看:27
本文介绍了标头变量的obj-c重复符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,使用#import 每次构建只会导入一次文件,但是在尝试在头文件中定义变量,然后将该头文件导入两个不同的源文件后,我得到一个重复的符号链接器错误变量.这怎么可能?

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?

推荐答案

#import 使每个 文件 包含一次标头,而不是每个构建.因此,您的变量是在您导入标头的每个文件中定义的,并且由于默认情况下全局变量在整个项目中可见,您会收到链接器错误.
定义全局变量的正确方法(如果它是您想要做的)是在实现文件中定义它,并在其他文件中使用关键字 external 来引用它.
同时将标头中的变量定义为静态将限制其对单个文件的可见性,因此您不会收到错误,但可能不是您想要的结果;)

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

这篇关于标头变量的obj-c重复符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆