Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, Is it good form to write code that executes before main()?

The constructors of globally declared classes are invoked before main is entered. While this can be confusing to a new reader of the code because it is done so infrequently, is it necessarily a bad idea?

like image 527
Bruce Avatar asked Jun 24 '10 14:06

Bruce


People also ask

What happens before main () is called in C?

For most C and C++ programs, the true entry point is not main , it's the _start function. This function initializes the program runtime and invokes the program's main function. The use of _start is merely a general convention. The entry function can vary depending on the system, compiler, and standard libraries.

Is it possible to execute some code before main function starts executing?

In object-oriented languages (C++) you can execute code before main() by using a global object or a class static object and have their constructors run the code you want.

Can we call function before Main?

Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method. Hence we can easily call the function before the main().

Is the main function always compiled first?

The function main is always compiled first, regardless of where in the program the function main is placed. Using functions greatly enhances a program's readability because it reduces the complexity of the function main.


3 Answers

It's not necessarily a bad idea, but usually, yes.

First, it's global data, and globals are usually a bad thing. The more global state you have, the harder it becomes to reason about your program.

Second, C++ doesn't guarantee intialization order of static objects defined in different translation units (.cpp files) -- so if they depend on one another, you might be in trouble.

like image 66
jalf Avatar answered Oct 29 '22 19:10

jalf


Yes, this is bad. Since you will have no way to catch exceptions and deal with them, the default handler will be used. In C++ that means calling terminate...

Example: contents a.cpp

#include <stdexcept>

int f() { throw std::runtime_error("boom"); return 42; }
int i = f();

int main(int argc, char* argv[])
{
  return 0;
}

Output of : g++ a.cpp && ./a.out

terminate called after throwing an instance of 'std::runtime_error'
  what():  boom
Aborted (core dumped)

You can try add a try ... catch in your main, that won't help.

Edit: Jalf's points are valid too. Listen to his advice.

like image 28
bltxd Avatar answered Oct 29 '22 20:10

bltxd


In addition to being of questionable form - It will not be portable to some platforms.

like image 35
Ofir Avatar answered Oct 29 '22 18:10

Ofir