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.
-
What platform are you writing for? – Joe May 10 '13 at 13:19
-
1Can 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
-
3Just 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 Answers
If you are using GCC, you can create construtors/destructor functions:
The
constructor
attribute causes the function to be called automatically before execution entersmain()
. Similarly, thedestructor
attribute causes the function to be called automatically aftermain()
completes orexit()
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

- 8,183
- 25
- 43
-
1+1. And here is an example: http://www.geeksforgeeks.org/functions-that-are-executed-before-and-after-main-in-c/ – Tomislav Dyulgerov May 10 '13 at 13:26
There is atexit
function in C (std::atexit
in C++) which registers a function to be called at program termination.

- 142,963
- 15
- 272
- 331
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.

- 7,378
- 4
- 37
- 54
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?

- 2,880
- 13
- 19