可以为公用变量和方法创建公用类,也可以用公用文件,如下:
头文件 CommParam.h:
代码
1
//
标准方式定义enum
2 enum E1{
3 A1 = 1 ,A2
4 };
5
6 // 用typeof定义E2
7 typedef enum {
8 B1 = 10 ,B2
9 } E2;
10
11 // 定义公用变量
12 extern int count;
13
14 // 定义公用变量(其实是常量)
15 extern const int CALLNUM;
16
17 // 定义C语言方法(可以在其中用Objective-c的对象和方法)
18 extern void hello(NSString * name);
2 enum E1{
3 A1 = 1 ,A2
4 };
5
6 // 用typeof定义E2
7 typedef enum {
8 B1 = 10 ,B2
9 } E2;
10
11 // 定义公用变量
12 extern int count;
13
14 // 定义公用变量(其实是常量)
15 extern const int CALLNUM;
16
17 // 定义C语言方法(可以在其中用Objective-c的对象和方法)
18 extern void hello(NSString * name);
源文件 CommParam.m(文件名可以不是CommParam.m):
1
#import
"
CommParam.h
"
2
3 // 为count赋初始值
4 int count = 1 ;
5
6 // 为CALLNUM赋初始值
7 const int CALLNUM = 10 ;
8
9 // 实现hello方法
10 void hello(NSString * name) {
11 NSLog( @" hello, %@ " , name);
12 }
2
3 // 为count赋初始值
4 int count = 1 ;
5
6 // 为CALLNUM赋初始值
7 const int CALLNUM = 10 ;
8
9 // 实现hello方法
10 void hello(NSString * name) {
11 NSLog( @" hello, %@ " , name);
12 }
测试文件 Test.m:
代码
1
#import
<
Foundation
/
Foundation.h
>
2 #import " Fraction.h "
3 #import " Fraction2.h "
4 #import " CommFun.h "
5 #import " CommParam.h "
6 int gGlobalVar = 5 ;
7
8 int main ( int argc, const char * argv[]) {
9 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
10 hello( @" Tom " );
11 enum E1 e1 = A1;
12 E2 e2 = B1;
13 NSLog( @" this is E1 object value:%i " ,e1);
14 NSLog( @" this is E2 value:%i " ,e2);
15 NSLog( @" CALLNUM:%i " ,CALLNUM);
16 count ++ ;
17 NSLog( @" count:%i " ,count);
18 [pool drain];
19
20 return 0 ;
21 }
2 #import " Fraction.h "
3 #import " Fraction2.h "
4 #import " CommFun.h "
5 #import " CommParam.h "
6 int gGlobalVar = 5 ;
7
8 int main ( int argc, const char * argv[]) {
9 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
10 hello( @" Tom " );
11 enum E1 e1 = A1;
12 E2 e2 = B1;
13 NSLog( @" this is E1 object value:%i " ,e1);
14 NSLog( @" this is E2 value:%i " ,e2);
15 NSLog( @" CALLNUM:%i " ,CALLNUM);
16 count ++ ;
17 NSLog( @" count:%i " ,count);
18 [pool drain];
19
20 return 0 ;
21 }