Objective-C中的const extern static用法

  • extern
    下面的代码声明了一个全局变量,它用于告诉编译器:“你现在编译的文件中,有一个标识符虽然没有在本文件中定义,但是它是在别的文件中定义的全局变量,你要在其它文件内查找!”
extern int a;//声明一个全局变量a

但是如果该变量没有在其他文件中定义,则会报错

Undefined symbols for architecture arm64:
  "_b", referenced from:
      -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
  • const
    使用const在任意文件中定义 ,外部都能访问。并且编译时会进行类型检查。
//A.h
const NSString *SUNName = @"酷酷的哀殿";

但是在其它文件使用前,需要使用extern声明。

//B.m
  extern NSString *SUNName;
  NSLog(@"%@",SUNName);
  • static
    • 在全局变量前,加上关键字static,该变量就被定义成为一个静态全局变量。
    • 静态全局变量在声明它的整个文件都是可见的,而在文件之外是不可见的。
    • 静态变量都在全局数据区分配内存。
  static NSString *name;
  name = @"酷酷的哀殿";
  NSLog(@"%p", name);

  NSString *nameba = @"酷酷的哀殿";
  NSLog(@"%p", &nameba);

  NSString *nameb = @"酷酷的哀殿";
  NSLog(@"%p", &nameb);

静态变量和局部变量的地址并不在同一个区域

0x1000ec070
0x16fd1a1f8
0x16fd1a1f0

下面两种全局变量声明的区别是,如果多个文件内存在同名变量,int a会导致duplicate symbol _a

static int a;

int b;
  • 其它用法
    为了方便让外部使用变量,推荐使用以下方法
    在.h文件内进行如下声明
 FOUNDATION_EXTERN NSString *const kSUNName;
 //或
 UIKIT_EXTERN NSString *const kSUNName;

并在.m文件内定义

NSString *const kSUNName = @"酷酷的哀殿";

用static const修饰后,不能提供外界访问。

static const NSString *SUNName = @"酷酷的哀殿";

在其他地方使用会报错

Undefined symbols for architecture arm64:
  "_SUNName", referenced from:
      -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值