【发布时间】:2014-12-24 10:48:19
【问题描述】:
假设我有这样的功能:
static int init_processing(char *buf, FILE *stream, enum operationMode mode) {
/* save index of `stream' in current operations */
/* start processing */
/* save some important variables for continue_processing */
off_t position;
enum operationMode _mode;
return num_processing_operations_left;
}
.. 我偶尔会打电话。我还有另一个函数可以执行我想要的实际处理:
static int continue_processing(FILE *stream) {
/* lookup the index of `stream' in current operations */
/* do some stuff */
/* save some static variables */
static off_t left = position;
static void *some_ptr;
return --num_processing_operations_left;
}
我还有一个清理函数可以在完成某个操作时调用:
static int end_processing(FILE *stream) {
/* check */
if (num_processing_operations_left)
return 1;
/* clean everything */
return 0;
}
如您所见,这种相关函数技术非常熟悉,它被标准库本身使用(例如 [malloc、free、realloc]、[fdopen、fopen、fclose])。
我想在这里实现的是如何在一堆函数之间共享一些变量?
我想到了两个解决方案:
将每组函数放在自己的文件中,提供仅对文件本身有效的静态变量。
仅使用一个将额外枚举参数作为模式的函数并相应地构造函数。
但这些解决方案实际上并不是解决方案,它们只是解决问题的变通方法。那么,是否有任何标准技术可以在函数之间共享变量?
【问题讨论】:
标签: c architecture functional-programming scope