Reputation: 943
I have the following code:
struct str {
int a;
int b;
};
extern struct str c;
In assembly (with GNU as), I can set the memory location of c
like so:
.global c
.set c, 0x12345678
Is there a way to portably do this in C? This code is for a microcontroller, so I wouldn't consider it a "bad practice".
Upvotes: 1
Views: 115
Reputation: 490518
Yes and no. You can write code that should compile with essentially any compiler. What happens after that will depend though.
struct str *c = (struct str *)0x12345678;
As I said, this much should compile with just about any compiler (though it could be rejected if the number you use is one the compiler doesn't think can be turned into an address). When you attempt to dereference the pointer will depend on how the compiler translates that to an actual address (varies, but intended to be what somebody who knows addressing for the machine will expect) and whether the address it generates is one to which you actually have access (and if so, exactly what access you have).
Upvotes: 2