How do I call main() in my main cpp file from a seperate cpp file?

青春壹個敷衍的年華 提交于 2019-12-02 13:37:14

In C++ it is illegal for a program to call main itself, so the simple answer is you don't. You need to refactor your code, the simplest transformation is to write a loop in main, but other alternatives could include factoring the logic out of main into a different function that is declared in a header and that you can call.

you don't, change the return value of dispMessage to an int or similar, from the main you check the return code and do different actions based on that.

main is special, you're not allowed to call it in C++.

So the "obvious" thing to do is to move everything to another function:

int my_main()
{
    Message DisplayMessage;
    DisplayMessage.dispMessage();
    return 0;
} 

int main() 
{
    return my_main();
}

Now you can call my_main from anywhere you like (as long as you declare it first in the translation unit you want to call it from, of course).

I'm not sure whether this will really solve your problem, but it's as close as possible to calling main again.

If you call my_main from somewhere else in your program then you won't exactly be "returning to the start", you'll be starting a new run through the code without having finished the old one. Normally to "return to the start" of something you want a loop. But it's up to you. Just don't come crying to us if you recurse so many times that you run out of stack space ;-)

Maybe something like that:

bool dispMessage(void)
{
  cout << "This is my message" << endl;
  // call me again
  return true;

  // do not call me again
  return false;
}

and in the int main():

int main()
{
  Message DisplayMessage;
  while(DisplayMessage.dispMessage())
  {

  }
  return 0;
} 

Assuming that you could change dispMessage(void) to something like bool askForReturnToStart() then you could use that to build a loop within main, f.e.:

int main() {
  Message dm;
  do {
    // whatever
  } while (dm.askForReturnToStart());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!