如何避免在使用此配置的每个函数中传递配置变量

时间:2014-05-07 18:44:58

标签: c ansi

如何避免在使用此配置的每个函数中传递“config”变量。 做出这种行为的最准确方法是什么。

这是我的代码: main.c中

/* Complex Numbers Linking to proper variable */
typedef struct tagConfigNames {
    char name;
    complex *cnum;
} config_names;

/* Set command to function */
struct {
    char *name;
    void (*func)(config_names[]);
} cmd[] = {{"read_comp", read_comp}, {"print_comp", print_comp}, {"halt", halt},{"not_valid", NULL} };

int main()
{
    complex a,b,c,d,e,f;
    config_names cnumbers []= {{'a', &a}, {'b', &b}, {'c', &c}, {'d', &d}, {'e', &e}, {'f', &f},
                {'A', &a}, {'B', &b}, {'C', &c}, {'D', &d}, {'E', &e}, {'F', &f},
                {'#', NULL}};
    char command[30];
    int i;

    /* Run Forever */
    while(1) 
    {
        if (scanf("%s", command) == 1) {
            for (i = 0; cmd[i].func != NULL; ++i) {
                if (strcmp(command, cmd[i].name) == 0) 
                    break;
            }

            if (cmd[i].func == NULL) {
                printf("Error: no such command!\n");
            } else {
                (*(cmd[i].func))(cnumbers);
            }
        }
    }

    return 0;
}

complex.c里

complex* find_complex_number(config_names cnames[], char ch)
{
    int i;
    for (i = 0; cnames[i].cnum != NULL; i++) {
        if (cnames[i].name == ch)
            break;
    }

    return cnames[i].cnum;
}

void read_comp(complex_names cnames[]) 
{
    //....

    if ((complex_num = find_complex_number(cnames, ch)) == NULL) {
        printf("Error: No such complex number\n");
        return;
    }
    //....
}

我正在努力避免的是config_names cnumbers在每个函数中传递。 是否有更聪明的方法来处理这种行为?

编辑:

我需要声明复数a,b,c,d,e,f;仅在main.c文件上。这就是为什么我要避免全局变量

3 个答案:

答案 0 :(得分:3)

如果" 配置"对于您可能考虑全局定义它的应用程序的每个线程,它是常量。

答案 1 :(得分:2)

如果每个线程的配置都是常量,或者您没有使用线程,则可以使用全局变量。否则你可以使用Thread Local Storage,它就像一个全局变量,但特定于每个线程。

答案 2 :(得分:1)

要扩展上述内容,您可能希望在文件中收集所有依赖于此的函数,并在其中创建全局(或线程局部)变量static,以便将解决方案保持在最低限度。