如何从C中的其他函数调用main() [英] How to call main() from other functions in C

查看:140
本文介绍了如何从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:

  1. 在C语言中,我们可以通过其他函数调用main()函数.
  2. 在C ++中,我们无法通过其他函数调用main()函数.
  1. In C, we can call main() Function through other Functions.
  2. 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);
}

这篇关于如何从C中的其他函数调用main()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆