• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在“未使用的变量"使用类型化常量警告?

用户头像
it1352
帮助1

问题说明

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

我对简单地取消所有未使用的变量警告不感兴趣,因为我确实想获得合法的警告.

正确答案

#1

在标题中声明 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
系列文章
更多 icon
同类精品
更多 icon
继续加载