4

i have a question for you. I need find out if i can use some function before or after main() function ended. I can't find some examples for C language. Can you give me some advice or examples. Thanks a lot.

Fortunes
  • 43
  • 1
  • 3
  • What platform are you writing for? – Joe May 10 '13 at 13:19
  • 1
    Can you not just put the code at the end of `main`? We need more info to provide a truly useful solution. Also, do you need C++ or C, because in C++ you have constructors and destructors available to you. – Mark B May 10 '13 at 13:20
  • 3
    Just rename `main()` to eg `oldmain()` and in the new `main()` call `oldmain()` and other functions as needed. – pmg May 10 '13 at 13:21
  • http://en.cppreference.com/w/cpp/utility/program – stardust May 10 '13 at 13:21

4 Answers4

10

If you are using GCC, you can create construtors/destructor functions:

The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() completes or exit() is called. Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.

Sample:

void __attribute__ ((constructor)) ctor() { printf("1"); }
void __attribute__ ((destructor))  dtor() { printf("3"); }
int main() { printf("2"); }

Output:

123
Guilherme Bernal
  • 8,183
  • 25
  • 43
9

There is atexit function in C (std::atexit in C++) which registers a function to be called at program termination.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

You could use atexit() for normal program exit, a signal handler (in UNIX) for abnormal exit.

GCC also has the constructor and destructor function attributes that do what you want, that's not vanilla C or C++ though.

Joe
  • 7,378
  • 4
  • 37
  • 54
1

There are many solutions to this problem, some of which have been provided:

  • Static CRT intitialization/termination (static object destructor "hook")
  • Renaming your main and wrapping it with the real main
  • Registering a hook with atexit()

It's not clear what you're trying to do, or even whether the question intends "can I do it" or "is it safe to do it"? Can you clarify?

Scott Jones
  • 2,880
  • 13
  • 19