The compiler can and will probably exclude (ignore) the unused declaration of the volatile variable (but the compiler cannot eliminate the unused definition of the global variable - it must assume that some other translation unit (TU) will refer to it).
If the variable is local to the function and is not used, it can be eliminated by the compiler, regardless of its volatility. It is not clear that you may have significant local mutable variables, although, I suppose, you could call a function that passes its address to some code, which then arranges an interrupt handler to write to this variable - achieving volatility (but then, the variable used) .
The volatile qualifier controls (affects) how the compiler generates code that accesses the variable - if the code does not have access to the variable, there is no need to change the code that it generates, except to avoid creating a reference to the variable. It also cannot be.
Further thoughts:
If the variable is static volatile and is not specified in the source code, can it be eliminated?
The answer (almost certainly) is yes. There is no reference to a variable in the source, and the only ways that you can access it in portable mode require a reference to it. Possible unauthorized hacks include defining several of these static variables and passing a reference to one of them to some function, and this function then expects to be able to access other variables by manipulating addresses. However, such code is awful and non-portable at best. The author of this, probably, should be taken out somewhere and quietly dissuaded from writing such code again.
Thus, the definition of a global variable cannot be eliminated; other TUs may refer to it. A static definition of a variable that is not used can be eliminated. A local definition of a variable that is not used can be eliminated. And this applies to whether the variable in question has a volatile qualifier or not.
source share