If it fails with "undefined reference to \`saved_sp' " (which is really a *linker* error, not a compiler error) when `saved_sp` is `static`, but works when it is not, then it seems likely that the compiler has decided that `saved_sp` is not used in your source file, and has therefore decided to omit it completely from the compiled code that is passed to the assembler.
The compiler does not understand the assembly code inside the `asm` block; it just pastes it into the assembly code that it generates. So it does not know that the `asm` block references `saved_sp`, and if nothing else in the C code ever reads from it, it is at liberty to decide that it is completely unused - particularly if you have any optimisation options enabled.
You can tell `gcc` that `saved_sp` is used by something that it can't see, and therefore prevent it from choosing to throw it away, by adding the `used` attribute (see the [documentation of variable attributes](
[To see links please register here]
), about half-way down the page), e.g.:
static long __attribute__((used)) saved_sp;
Here's a fully worked example:
$ cat test.c
#ifdef FIXED
static long __attribute__((used)) saved_sp;
#else
static long saved_sp;
#endif
int main(void)
{
__asm__ __volatile__ (
"movq saved_sp, %rsp\n\t" );
}
$ gcc -m64 -o test test.c
$ gcc -m64 -O1 -o test test.c
/tmp/ccATLdiQ.o: In function `main':
test.c:(.text+0x4): undefined reference to `saved_sp'
collect2: ld returned 1 exit status
$ gcc -m64 -DFIXED -O1 -o test test.c
$
(This is from a 32-bit Debian squeeze system with gcc 4.4.5, which is the closest thing I have to hand; `-m64` may well be unnecessary on your system.)