Two main functions

前端 未结 8 842
孤独总比滥情好
孤独总比滥情好 2020-12-19 10:20

Can we have two main() functions in a C++ program?

8条回答
  •  抹茶落季
    2020-12-19 10:48

    A program can only have one entry point, but of course that one main() function can call out to other functions, based on whatever logic you care to specify. So if you are looking for a way to effectively compile two or more programs into a single executable, you can do something like this:

    int main(int argc, char ** argv)
    {
       if (argc > 0)  // paranoia
       {
               if (strstr(argv[0], "frogger")) return frogger_main(argc, argv);
          else if (strstr(argv[0], "pacman"))  return pacman_main(argc, argv);
          else if (strstr(argv[0], "tempest")) return tempest_main(argc, argv);
       }
    
       printf("Hmm, I'm not sure what I should run.\n");
       return 10;
    }
    

    ... then just rename your 'other' main() functions to frogger_main(), pacman_main(), or whatever names you care to give them, and you'll have a program that runs as Frogger if the executable name has the word 'frogger' in it, or runs as PacMan if the executable has the name 'pacman' in it, etc.

提交回复
热议问题