Issue
GNU C global register variables can't have initializers. This won't compile as C or C++:
// at global scope.
register int i asm ("r12") = 10;
gives (Godbolt) error: global register variable has initial value
. Local scope is fine of course, but GNU C local register variables are a very different thing. (Only guaranteed to do anything in terms of interaction with Extended asm()
statements.)
Code
#include<stdio.h>
register int i asm ("r12"); //how to initialize i here?
int main()
{
i=10; // Would rather avoid this workaround
printf("%d\n",i);
}
How to initialize i
at global scope, not waiting until the top of main?
Solution
You can't initialize a global register variable.
The GCC documentation states this:
Global register variables cannot have initial values, because an executable file has no means to supply initial contents for a register.
Also note the paragraph below:
When selecting a register, choose one that is normally saved and restored by function calls on your machine. This ensures that code which is unaware of this reservation (such as library routines) will restore it before returning.
You should not use r12
, it is not saved across calls.
Answered By - S.S. Anne