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

查看:119
本文介绍了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 每个文件一次,但不是每个构建。所以你的变量是在你导入头文件的每个文件中定义的,并且在整个项目中默认情况下全局变量是可见的,你会得到链接器错误。

定义全局变量的正确方法(如果它是你想要做的)在实现文件中定义它,并用其他文件中的外部关键字引用它。

将标题中的变量定义为静态会将其可见性限制在单个文件中,因此您不会收到任何错误,但可能不是您想要的结果;)

#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天全站免登陆