在“未使用的变量"使用类型化常量警告?
问题说明
我使用的是 Xcode 4.6,我有一个头文件,其中包含我在整个代码中使用的一些常量.我不想使用预处理器指令,因为我希望它们的类型正确等等.
I'm using Xcode 4.6 and I've got a header file which includes some constants I use throughout my code. I don't want to use preprocessor directives because I want them to be properly typed and such.
例如,我的一个 .h 文件中有此代码:
For example, I have this code in one of my .h files:
static NSString *kErrorCannotDivideByZero = @"Error: Cannot divide by zero";
并且我在相应的 .m 文件中使用它:
and I use it in the corresponding .m file:
[self showToast:kErrorCannotDivideByZero];
我收到警告:
/path/to/my/headerFile.h:32:18: Unused variable 'kErrorCannotDivideByZero'
我知道这只是一个警告,但是我有大约 50 个这样的警告阻塞了我的编译器输出.
I know it's just a warning, but I've got about 50 of these warnings clogging up my compiler output.
为什么我会收到此警告,我该如何正确解决?
Why am I getting this warning and how do I PROPERLY resolve it?
我对简单地取消所有未使用的变量警告不感兴趣,因为我确实想获得合法的警告.
正确答案
在标题中声明 extern
而不是 static
.您正在做的是为包含您的标题的每个翻译单元创建一个变量,这就是 Clang 警告您的原因,因为它是合法的未使用的已定义变量.extern
关键字告诉编译器变量的定义可以在其他地方找到(它可能在同一个翻译单元中,也可能在另一个).
Make the declaration in your header extern
rather that static
. What you're doing is creating a variable for every translation unit that includes your header, and this is why Clang is warning you, because it is legitimately a defined variable that is not being used. The extern
keyword tells the compiler that the definition of the variable is found somewhere else (it might be in the same translation unit or it might be in another).
在您的标题中,有:
// declare that the constant exists somewhere
extern NSString * const kErrorCannotDivideByZero;
在一个的.m
文件中(通常是与标题同名的文件),放入
And in one of your .m
files (typically the one that shares the same name as the header), put
// define the constant, i.e. this is where it exists
NSString * const kErrorCannotDivideByZero = @"Error: Cannot divide by zero";
声明变量 extern
允许编译器确保您正确处理变量,即使它不知道变量在哪里定义(例如,您不能将其用作 NSArray).链接器的任务是确保您确实在某处定义了它.
Declaring variables extern
allows the compiler to ensure you are treating the variable correctly even if it doesn't know where it is defined (e.g. you can't use it as an NSArray
). The linker has the job of making sure you actually defined it somewhere.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfgcge
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22