Reputation: 12842
I'm doing some code generation. Is it possible to find the future address of a global C variable at compile time?
Suppose there is a global variable in a C file:
const char[] bytecode = "generated bytecode goes here";
After that, I need to add code pointing to bytecode
at compile time:
const char* ptrInsideBytecode = 0x1234 + offset;
// 0x1234 should be the address of bytecode
It is not an option to just refer to bytecode field, the pointer must be fixed.
I know that myVar will be at some fixed position after compilation and linking, so this should be possible. How do I find the exact address of bytecode
before compiling?
Upvotes: 1
Views: 1253
Reputation: 44240
const char bytecode[] = "generated bytecode goes here";
// After that, I need to add code pointing to bytecode at compile time:
#define offset 6
const char *ptrInsideBytecode = bytecode + offset;
// the address you want >>>-----^^^^^^^^
Upvotes: 0
Reputation: 11492
There isn't a way to do this, because the compiler must perform the summation in order to know what the value is, however the address won't be known until the linker has run.
Depending on your platform, you may be able to place your bytecode at a fixed location in memory by using a linker script. This is only likely to work if you're on a microcontroller that doesn't have an operating system.
Upvotes: 2
Reputation: 49803
It doesn't have an address at compile time; to see why, you could compile it on a different machine than the one (or more!) that it gets executed on.
Upvotes: 0