I think you're getting confused between the meaning of static
and const
which is understandable as you (and I!) often forget their meaning once you've read the theory once.
1) Firstly, const
. What const
means is that we won't change the value of the variable through this "reference" to it. This is really useful for function arguments, particularly when using pointers, so that you don't edit values you didn't intend to. For example, arbitrarily:
void add(int* result, const int* a, const int* b)
This declaration means if we accidentally typed a = result + b;
the compiler should complain and refuse to compile. In this case we've named the variables in such a way that we shouldn't overwrite them even by accident but in more complicated scenarios, it can happen.
As pmg says, however, this does not mean the value will not change; it simply means when talking about this version of that address/value we will not change it. My point here is that it is useful to protect arguments you don't intent to change in case you accidentally do try to change them. If you want a truly fixed value preprocessor is often used, e.g. #define TRUE 1
.
2) Now static
. Static means "not visible outside this compilation unit". This is like, and I stress like, but not equivalent to, the notion of private in classes, but in this case we're talking about the entire C file. So, if we are in file helloworld.c
and at the top you write:
static int x = 10;
You cannot then use that version of x
in helloworld2.c
.
3) Whilst we are at it, we might as well do the other word inline
. inline
is sort-of a nicer way to do macros in my opinion and means "compiler, you should really put the resultant code of this into wherever you call it, rather than costing us a function call". Optimising compilers might do this anyway but this acts as an explicit instruction to inline where possible.
In summary, these features all control parts of the language and not where the variable gets placed in the executable's various segments. As pmg says, the compiler can do whatever it likes.
If you want an idea of what the compiler has done, use gcc -S
. This gives you the assembly language output from gcc
which will be in AT&T format. Try this with different gcc -Ox
where x=0,1,2,3
flags to get an idea of how optimisation works.
Finally, it is worth noting that in fact a.out
is merely a name; your modern kernel is probably compiled without support for a.out
binaries.
I think that's the question you were really trying to ask.