简体   繁体   English

从C中的另一个函数调用main函数

[英]Calling main function from another function in C

I have a main function that runs a few functions during initialization and then runs a while loop that waits for commands from the UART. 我有一个main函数,它在初始化期间运行一些函数,然后运行一个while循环,等待来自UART的命令。

When I see a specific command (let's say reset), I call a function that returns a value. 当我看到一个特定的命令(让我们说重置)时,我调用一个返回值的函数。 I want to do the following things: 我想做以下事情:

  1. Save the returned value 保存返回的值
  2. Start the main function again with the returned value. 使用返回的值再次启动main函数。 The returned value is required during initialization of the functions in main. 在main中的函数初始化期间需要返回值。

I am newbie in C and I am not able to figure out a way save variable value in main. 我是C的新手,我无法想出一种在main中保存变量值的方法。

The way I understand things, you essentially have the following setup: 我理解的方式,你基本上有以下设置:

int main(int argc, char *argv[]) {
    int value = something_from_last_reset;
    perform_initialization(value);
    while(1) {
        int next_command = wait_for_command();
        if(next_command == RESET_COMMAND) {
            value = get_value();
            // somehow restart main() with this new value
        }
    }
    return 0;
}

Here's one approach you could take: 这是您可以采取的一种方法:

// global
int value = some_initial_value;

void event_loop() {
    while(1) {
        int next_command = wait_for_command();
        if(next_command == RESET_COMMAND) {
            value = get_value();
            return; // break out of the function call
        }
    }
}

int main(int argc, char *argv[]) {
    while(1) {
        perform_initialization(value);
        event_loop();
    }
    return 0;
}

This essentially lets you "escape" from the event loop and perform the initialization all over again. 这实际上允许您从事件循环中“转义”并重新执行初始化。

just wrap your main into infinity-loop. 将你的main包装成无限循环。

int main(void)
{
    int init_val = 0;
    while (1)
    {
        // your code ...
        init_val = some_function();
    }
}

In theory this is possible, but it kind of breaks paradigms, and repetitively calling a function without ever letting it finish and return will quickly fill up your call stack, unless you take measures to unwind it behind the compiler's back. 理论上这是可能的,但它有点打破范式,重复调用函数而不让它完成并返回将很快填满你的调用堆栈,除非你采取措施在编译器的后面展开它。

A more common solution would be to write your main() function as one giant infinite while {1} loop. 一个更常见的解决方案是将main()函数编写为一个巨大的无限{1}循环。 You can do all of your operation in an innner loop or whatever, and have clauses such that if you get your desired new value you can fall through to the bottom and loop back, effectively re-running the body of main with the new state. 你可以在一个内在的循环或其他任何东西中完成你的所有操作,并且有条款,如果你得到你想要的新值,你可以掉到底部并循环回来,有效地重新运行主体的新状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM