title: Call a specific function when the console program terminates
body: <p>I'm on windows and I want to call a specific function when the program terminates.</p>
  
  <p>For example:</p>
  
  <pre><code>void close_program()
  {
      /*do stuff*/
      printf("Goodbye.\n");
  }
  </code></pre>
  
  <p>I tried <code>atexit()</code> but it only worked on casual and regular exits such as a call to the function <code>exit()</code> or when the main returns a value to the OS.</p>
  
  <p>I found out that <code>HandlerRoutine()</code> seems like a solution as windows sends a <code>CTRL_CLOSE_EVENT</code> value signal to the process closed by the user (either just close button or end task through task manager). The problem is I tried a really basic piece of code and it said 'undefined reference to <code>HandlerRoutine</code>' and that it returned 1.</p>
  
  <p>The piece of code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;windows.h&gt;
  
  int main()
  {
      while(1)
      {
           if(HandlerRoutine(CTRL_CLOSE_EVENT))
           {
                printf("Program is being terminated...\n");
           }
       }
       return 0;
  }
  </code></pre>
  
  <p>I use MinGW.</p>
  
  <p>Any idea what is the problem might be ?</p>
  
  <p>According to <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683242(v=vs.85).aspx" rel="nofollow">MSDN</a> there is no need for linkage.</p>