IOS OC应用c的全局变量和全局函数

来源:互联网 发布:安装ubuntu盘符设置 编辑:程序博客网 时间:2024/06/05 15:31

// 定义数据结构的文件:

TableInfo.h

#ifndef TestMonitor_TableInfo_h

#define TestMonitor_TableInfo_h


typedef struct {

    char * testName;

}monitor_table;

#endif


************************************************************

// 定义全局变量和函数的c文件:

// 这个文件不能在多处 #import ,如果多处import,会导致里面的定义的全局变量和函数重复定义,编译不过

// 需要引用里面的全局变量的地方,只需要extern monitor_table Monitor_Table;就可以了, 使用方法参见下面的a.m 和 b.m


//  全局变量和函数,要放在.c文件里面

globalDefine.c:


#import "TableInfo.h"

#include <stdio.h>

// 全局变量定义的地方不能加extern, 否则其他地方会报未定义的变量

// 全局变量定义

monitor_table Monitor_Table;


// 全局方法定义

void initTable(char* str) {

       Monitor_Table.testName = str;

}


************************************************************

应用全局变量的文件 a.m 

#import "TableInfo.h"


// 引用全局变量的文件需要使用extern 引入,否则找不到全局变量, (全局函数不需要extern 引用也可以找到)

extern monitor_table Monitor_Table;

// 引入全局函数,这句不要也可以编译通过和正确执行,不会报找不到initTable函数的, 见b.m

extern void initTable(char*);


// 测试方法

- (void)testDbString {

    // 全局方法调用,貌似不需要extern也可以直接找到全局方法

    initTable("main screen caseName");


    char* str =Monitor_Table.testName;

    NSString* nstr = [[NSStringalloc]initWithCString:strencoding:NSASCIIStringEncoding];

    NSLog(@"testDbString -- nstr = %@, char* = %s", nstr, str);

}


应用全局变量的文件 b.m 

#import "TableInfo.h"


// 引用全局变量的文件需要使用extern 引入,否则找不到全局变量, (全局函数不需要extern 引用也可以找到)

extern monitor_table Monitor_Table;

// 引入全局函数,这句不要也可以编译通过和正确执行,不会报找不到initTable函数的

// extern void initTable(char*);


// 测试方法

- (void)testDbString {

    // 全局方法调用,貌似不需要extern也可以直接找到全局方法

    initTable("create case caseName");


    char* str = Monitor_Table.testName;

    NSString* nstr = [[NSString allocinitWithCString:str encoding:NSASCIIStringEncoding];

    NSLog(@"testDbString -- nstr = %@, char* = %s", nstr, str);

}




















0 0
原创粉丝点击