tags:

views:

800

answers:

9

This may be a short & simple question, but I've never found a satisfying answer to it:

What code does the main() function usually consist of in a large C++ project? Would it be an incorrect assumption to think that it is usually just initializing a (wrapping) class object and calling a function inside of it to set things off?

Why is main() not a method in the first place? Is it to preserve backwards-compatibility with C?

+1  A: 

The short answer: it depends. It may well create a few local objects that are needed for the duration of the program, configure them, tell them about each other and call a long running method on one of them.

A program needs an entry point. If main had to be a method on an object, what class type should it be?

With main as a global entry point it can choose what to set up.

Charles Bailey
+2  A: 

Mine usually do

  • Command-line parsing
  • Initialization of top-level objects
  • Exception handling
  • entering main 'exec' loop

As I understand it, int main(int argc, char *argv[]) is essentially a convention due to the C heritage. Never struck me as odd, but rather as useful. C++ extends C after all ... (and yes there are fine difference but that wasn't the question here).

Dirk Eddelbuettel
+1  A: 

Yes, the reason is backward compatibility. main is the only entry point allowed in a C program producing executables, and therefore in a C++ program.

As for what to do in a C++ main, it depends. In general, I used to:

  • perform global initialization (e.g. of the logging subsystem)
  • parse command line arguments and define a proper class containing them
  • allocate an application object, setting it up etc.
  • run the application object (in my case, an infinite loop method. GUI programming)
  • do finalization after the object has completed its task.

oh and I forgot the most important part of an application

  • show the splashscreen
Stefano Borini
A: 

You can use a static class member function in place of main with the MSVC++ compiler by choosing the entry point in the project settings, under the advanced linker options.

It really depends on your project as to what you want to place in there... if it is small you may as well put message loops, initialization and shutdown code in there. In larger projects you will have to move these into their own classes/functions or less have a monolithic entry point function.

jheriko
A: 

Not all C++ applications are OOP and either way all code requires some entry point to start from.

When I'm writing OOP code, my main() tends to include an object instantiation, maybe proceeded by some user input. I do it this way because I feel that the 'work' is meant to be done within an object, otherwise the code isn't written in the 'spirit' of OOP.

Dana the Sane
A: 

Really large projects tend not comprise only a single program. Hence there will be several executables each with their own main. In passing, it's quite common for these executables to communicate asynchronously via queues.

Yes each main does tend to be very small, initialising a framework or whatever.

Do you mean why is main() a function rather than a method of class? Well, what class would it be a method of? I think it's mostly C++'s heritage from C, but ... everything got to start somewhere :-)

djna
main is a function, not a method...
micmoo
Thanks, yes you're right.
djna
+8  A: 

In my code, it's basically a constructor call, possibly a method call, and some exception handling. This is the main for own of my projects (headers and comments omitted, and formatting messed up by SO, as usual):

int main( int argc, char * argv[] ) {
    int result = 0;
    try {
        CLIHandler ch( argc, argv );
        result = ch.ExecCommand();
    }
    catch( const Exception & ex ) {
        result = ExceptionHandler::HandleMyError( ex );
    }
    catch( const std::exception & ex ) {
        result = ExceptionHandler::HandleOtherError( ex );
    }
    catch( ... ) {
        result = ExceptionHandler::HandleUnknownError();
    }
    return result;
}
anon
Why not just replace all your `result = ` with `return `?
GMan
Wash your mouth out! Have you never heard of the requirement that in all well-structured code a function must have only one exit point???? But to be serious, my way is easier to debug, as you have a variable to inspect.
anon
Ah, I see lol. You scared me. I was like, "FUUU- what?!". I guess I've never had to inspect the return variable, my error handler prints it out along with the exception. Otherwise our code is the same.
GMan
+1 for the answer and +1 for the comment
Stefano Borini
+1 for a main I like and encourage everybody to use. Something I use is an exception handler that just call ExceptionHandler::handle() in the catch(...) clause. The handle method re-throw in a try-catch where you have the different exception handling. Simplier ? More readable ? Error handling centralized in a specific class ... Your taste ...
neuro
The "only one exit point" thing was a lot more relevant in C. In C++, with RAII, it's *usually* pointless (and exceptions pretty much undermine it anyway). I can see the point here, in main, though.
jalf
@jalf That was a JOKE! I also encourage the use of multiple exit points - it almost always makes the code clearer.
anon
A: 

I usually use main for reading in the command line, initializing global variables, and then calling the appropriate functions/methods.

Imagist
+1  A: 

My main() function often constructs various top-level objects, giving them references to one another. This helps minimize coupling, keeping the exact relationships between the different top-level objects confined to the main.

Often those top-level objects have distinct life cycles, with init(), stop(), and start() methods. The main() function manages getting the objects into the desired running state, waits for whatever indicates it is time to shut down, and then shutting everything down in a controlled fashion. Again, this helps keep things properly decoupled, and keeps top-level life cycle management in one easily understood place. I see this pattern a lot in reactive systems, especially those with a lot of threads.

rtenhove