目标c中c文件的共享实例?

时间:2014-03-06 08:05:36

标签: ios objective-c c

我正在研究 C / Objective-C 中的国际象棋引擎,我用直接重写了我的大部分引擎以提高速度。我的问题是,我在我的C文件中初始化了大约3KB的表,我不希望每次调用此文件中的函数时都重新初始化。如果这是一个常规的Objective-c类,我会创建一个共享实例。但是,我的引擎的核心是两个 .h 和一个 .c 文件。 我应该让我的引擎使用的所有表格都是静态的吗?它们会在我的引擎中调用函数的多个其他文件之间存在吗?我应该创建一个静态结构来保存我的表吗?我不确定这里最好的方法是什么。谢谢!

示例:

Test.h:

int getInt(int index);

TEST.C:

static int integers[4] = {1,2,3,4};
int getInt(int index) { return integers[index]; }

每次我从另一个文件调用getInt时,它会重新分配'整数'吗?或者它会重用相同的数组吗?我想防止它不必要地重新分配一堆静态数组。

1 个答案:

答案 0 :(得分:0)

好的,你所做的是静态变量的访问器......

静态仅初始化一次,因此每次启动时只会初始化一次。 您可以保持这种方式,或者将其更改为全局访问它而无需调用函数。

此代码通常可以内联,因此将其更改为全局更多的是品味而不是表现。

Edit: short summary on allocations

static int array[] = {1, 2}; // Allocated and initialized once
int array2[] = {1, 2, 3}; // Allocated and initialized once

int function() {
 int array3[] = {1, 2, 3}; // Allocated and initialized at every call of function();
 static int *array4 = malloc(42); // Allocated and initialized once
 int *toto = malloc(42); // Allocated at every call of function();
}