gcc __未使用的标志行为/用法(愚者与Objective-C)

gc0ot86w  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(124)

我刚刚学习了__unused标志,它可以在用愚者编译时使用,我对它了解得越多,我的问题就越多...
为什么这个编译器没有警告/错误?奇怪的是,我特别告诉编译器我不会使用变量,然后当我使用它时,事情就正常进行了。

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self foo:0];
}

- (void)foo:(NSInteger)__unused myInt
{
    myInt++;
    NSLog(@"myInt: %d", myInt);  // Logs '1'
}

另外,下面两个方法签名之间有什么区别?

- (void)foo:(NSInteger)__unused myInt;

- (void)foo:(NSInteger)myInt __unused;
ecbunoof

ecbunoof1#

__unused宏(实际上扩展为__attribute__((unused))愚者属性)只告诉编译器“如果我不使用此变量,不要警告我”。
unused:这个属性附加在一个变量上,意味着这个变量可能没有被使用。愚者不会为这个变量生成警告。(来源:gnu.gcc.org文件)
所以这个愚者属性是为了避免警告当你不使用变量时,不触发一个警告当你使用你声称未使用的变量时。
至于在上一个示例中将属性放在变量名之前或之后,这两种情况都是可以接受的,并且在您的示例中是等效的:编译器只是出于兼容性的考虑而对位置比较宽松(就像您也可以编写const int iint const i一样)
为了与为未在嵌套声明符上实现属性的编译器版本编写的现有代码兼容,允许在属性的放置方面有一些宽松 (来源:gnu.gcc.org文件)

nbysray5

nbysray52#

从Xcode 7.3.1开始,以下各项之间目前没有区别:

- (void)foo:(NSInteger)__unused myInt;// [syntax 1]
- (void)foo:(NSInteger __unused)myInt;// [syntax 2]
- (void)foo:(__unused NSInteger)myInt;// [syntax 3]

但以下方法不起作用:

- (void)foo:(NSInteger)myInt __unused;// [doesn't work]

对于此用法,Apple建议使用第一种语法。(information was partially taken from this answer
但有区别:

__unused NSString *foo, *bar;  // [case a] attribute applies to foo and bar
NSString *foo __unused, *bar;  // [case b] attribute applies to foo only

NSString * __unused foo, *bar; // [case c] attribute applies to foo only
NSString __unused *foo, *bar;  // [case d] attribute applies to foo and bar
CFStringRef __unused foo, bar; // [case e] attribute applies to foo and bar

如果我们想让__unused适用于所有人,语法[a]是我个人最好的,因为它没有歧义。
如果我们想让__unused适用于一个,语法[B]是我个人最好的,因为它没有歧义。
后三种解决方案是可以接受的,但在我看来令人困惑。(information was partially taken from this answer
当我们讨论关键词的顺序时,请注意:

const NSString *foo = bar;  // BAD: foo is NOT const
NSString const *foo = bar;  // BAD: foo is NOT const
NSString *const foo = bar;  // GOOD: foo is const

相关问题