如何从C中的其他函数调用main()
我正在经历C和C ++的差异,我发现了一个棘手的问题.您能否详细说明以下几点:
I was going through the difference in C and C++ and I found a tricky point. Can you please elaborate the below points:
- 在C语言中,我们可以通过其他函数调用
main()
函数. - 在C ++中,我们无法通过其他函数调用
main()
函数.
- In C, we can call
main()
Function through other Functions. - In C++, we cannot call
main()
Function through other functions.
如何从另一个函数调用main()
,它的用例是什么?
How to call main()
from another function and what is the use case of it?
@TrevorHickey碰到了头(他的答案去了哪里?)-C ++禁止从其他函数中调用main
(出于充分的理由) ...并不是说有任何编译器可能会阻止您(我认为大多数人都不在乎).
@TrevorHickey hit the nail on the head (where did his answer go?) - C++ forbids calling main
from within a different function (for good reason)... Not that any compiler is likely to stop you (I don't think most of them care).
一个明显的解决方法是将main
的功能移到容器函数中,然后按照@KlasLindbäck的建议从那里调用它.
An obvious workaround would be to move main
's functionality into a container function and call it from there, as suggested by @KlasLindbäck.
即
int my_application(int argc, char const * argv[]) {
// do stuff
return 0;
}
int main(int argc, char const * argv[]) {
return my_application()
}
另一个可能仅由于编译器允许您调用main
的"hack"(正如@KlasLindbäck在注释中指出的那样)将使用函数指针.即
Another "hack" that probably only works because compilers let you call main
anyway (As also pointed out by @KlasLindbäck in the comments), would be to use function pointers. i.e.
int main(int argc, char const * argv[]) {
// do stuff
}
// shouldn't compile... but hey, you never know.
int (*prt_to_main)(int, char const* argv[]) = main;
void test_run(void) {
prt_to_main(0, NULL);
}