There was a lot said and written about volatile variables, and their use. In those articles, two slightly different ideas can be found:

1 - Volatile should be used when variable is getting changed outside of the compiled program.  

2 - Volatile should be used when variable is getting changed outside the normal flow of the function.

First statement limits volatile usage to memory-mapped registers etc. and multi-threaded stuff, but the second one actually adds interrupts into the scope.

This article (<http://www.barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword>) for example explicitly states that volatile modifier should be used for globals changed during the interrupt, and provides this example:

```
int etx_rcvd = FALSE;

void main() 
{
    ... 
    while (!ext_rcvd) 
    {
        // Wait
    } 
    ...
}

interrupt void rx_isr(void) 
{
    ... 
    if (ETX == rx_char) 
    {
    etx_rcvd = TRUE;
    } 
    ...
}

```

Note how setting up a rx\_isr() as a callback is conveniently omitted here.
Hence I wrote my own example:

```
#include <stdio.h>
#include <time.h>
#include <signal.h>

void f();

int n = 0;

void main() 
{
    signal(2,f);
    time_t tLastCalled = 0;
    printf("Entering the loop\n");
    while (n == 0) 
    {
        if (time(NULL) - tLastCalled > 1)
        {
            printf("Still here...\n");
            tLastCalled = time(NULL);
        }
    }
    printf ("Done\n");
}

void f() 
{
    n = 1;
}

```

Compiled with gcc on linux with various levels of optimizations, every time loop exited and I saw "Done" when I pressed ctrl+c, which means that really gcc compiler is smart enough not to optimize variable n here.

That said, my question is:  

If compiler can really optimize global variables modified by an interrupt service routine, then:  

1. Why it has a right of optimizing a global variable in the first place when it can possibly be called from another file?  

2. Why the example article and many others on the internet state that the compiler will not "notice" the interrupt callback function?  

3. How do I modify my code to accomplish this?