从C中的另一个函数调用主函数 [英] Calling main function from another function in C
问题描述
我有一个主要功能,该功能在初始化期间运行一些功能,然后运行一个while循环,等待来自UART的命令.
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.
当我看到一个特定的命令(比如说reset)时,我调用一个返回值的函数.我想做以下事情:
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:
- 保存返回值
- 使用返回的值再次启动主函数.在main中的函数初始化期间需要返回的值.
我是C语言的新手,无法找到一种在main中保存变量值的方法.
I am newbie in C and I am not able to figure out a way save variable value in 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.
这篇关于从C中的另一个函数调用主函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!