iOS 编译器__Attribute__的入门指南

本文介绍了iOS开发中编译器Attribute的使用,包括内存对齐、强制内联、规范提醒等功能,以及clang新增的特性,如弃用声明和C++函数重载。通过示例展示了Attribute如何用于函数优化、安全提示和代码混淆加固等场景。
摘要由CSDN通过智能技术生成

作者:小朋鸟

一、Attribute

Attribute 是 GNU C 的一大特色。
所以这对于iOS来说这是一个什么东西?

  • 这是一个可以给对象或函数声明特性的编译器指令,目的是让编译器做更多的错误检查和优化。
  • 可设置函数属性(Function Attribute)、变量属性(Variable Attribute)、类型属性(Type Attribute)

Swift 文档中的说明:

Attributes provide more information about a declaration or type. There are two kinds of attributes in Swift, those that apply to declarations and those that apply to types.

属性提供关于声明或类型的更多信息。Swift中有两种属性,一种应用于声明,另一种应用于类型。

引用:Attributes

二、使用方法

以下列举一下要怎么使用,大概的场景是什么。

1、内存对齐,深度优化

// aligned 用来调整内存对齐中每行的位数
// 如果设置少于4,编译器会自动优化成4
// 最大也只能是8
struct stu{
    char sex;
    int length;
    char name[2];
    char value[16];
}__attribute__((aligned(16)));

struct stu my_stu;

NSLog(@"%lu", sizeof(my_stu));
NSLog(@"%p %p,%p,%p", &my_stu,&my_stu.length,&my_stu.name,&my_stu.value);
NSLog(@"Hello, World!");

2、强制内联

减少函数调用,不过要注意递归方法不能用内联。

// 如果使用 __attribute__((always_inline))
// 汇编中会减少callq的方法
__attribute__((always_inline)) void inlineFunction(){
    int a = 10; a+= 10;
}

void testInline(){
    inlineFunction();
}

testInline();

对于以上两点,你可以永远相信编译器,除非哪一天它欺骗了你。那你再去尝试优化。

3、规范提醒

可以直接通过警告或者报错,提醒别人不能这样做!

/* 
    OC中可以是用 #param mark - xxxx
    swift使用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值