Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between volatile & extern?

Few days back i had an interview but, still I am searching for the answer. I would like to understand the significance of using volatile keyword.

Find the code below: Two different scenario.

//project1
//File1.c

int abc;//Global variable
/*And this variable is getting used in some other files too.*/
if(abc == 3) //Say
{
  printf("abc == 3");
}
else
{
  printf("abc != 3");
}
/*So if or else part will not be optimized 
because "abc" can not be predicted, 
the value can chage at any point of time */




//Project2
//file1.c

volatile int abc;//Global variable with volatile keyword

/*And this variable is getting used in some other files too.*/

if(abc == 3) //Say
{
  printf("abc == 3");
}
else
{
  printf("abc != 3");
}
/*So if or else part will not be optimized 
because "abc" can not be predicted as it is declared as volatile,
the value can chage at any point of time */

Why we should use volatile keyword instead?

like image 621
Rasmi Ranjan Nayak Avatar asked Feb 07 '12 09:02

Rasmi Ranjan Nayak


2 Answers

As Tony Delroy explained in its comment, extern and volatile are quite different.


Volatile keyword protects your variable from being aggressively optimised. An optimised variable can be invisible to other threads and never reach main memory. Sometimes, compiler can even squeeze entirely a variable if it's not needed. Compiler base its guess with your source code as its only input. Sometimes, there is some external events which can change your variable value. It could be an hardware device or an other process, for instance.

=> Concretely, compiler disables some optimisations to this variable, so it can behave as you want it to.


Extern is not about cache vs memory. Extern is just about accessing a variable which lives in an other object files. See this short example of what kind of assembly code is generated for an extern access. Those extern variables are optimised in their own object file as far as it's possible. There's no question about to protect it or not.

=> Concretely, compiler indicates an external reference needing to be solved at link time

like image 89
Coren Avatar answered Sep 22 '22 00:09

Coren


volatile in declaration or prototype say always load/store value from/to memory regardless local, static or extern this vlaue (but in case of local it is not always meaningful).

Also using volatile keyword in regular source are untypically. It is useful only for hardware which map hardware registers to memory (like in ARM architecture), in special cases of kernel/driver development.

If you use volatile in GUI or ecommerce code you probably wrong...

like image 37
gavenkoa Avatar answered Sep 18 '22 00:09

gavenkoa