天天看點

IOS OC應用c的全局變量和全局函數

原文位址::https://blog.csdn.net/miaojunking/article/details/45492037

相關文章

1、iOS屬性、全局變量聲明----https://www.jianshu.com/p/d3c80359f9d3

2、iOS全局常量----https://www.jianshu.com/p/80bab8340c45

3、IOS學習之ios全局變量定義和使用----https://blog.csdn.net/u010963948/article/details/48464297

4、OC中的全局變量和靜态變量----https://blog.csdn.net/showgp/article/details/51067413

5、iOS中全局變量的幾種使用方法----https://blog.csdn.net/u010719522/article/details/53307812

// 定義資料結構的檔案:

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 alloc] initWithCString:str encoding:NSASCIIStringEncoding];

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

}