如何在“未使用的变量"中使用类型化常量警告? [英] How to use typed constants with "unused variable" warnings?

查看:64
本文介绍了如何在“未使用的变量"中使用类型化常量警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 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.

这篇关于如何在“未使用的变量"中使用类型化常量警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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