Can I read from or write to a variable defined in my assembly file in my C file? I couldn't figure it out on my own. For example the C file looks as follows:
int num = 33;
and produces this assembly code:
.file "test.c"
.globl _num
.data
.align 4
_num:
.long 33
As i started to learn assembly i heard often the speed is the reason why i have to pick assembly and lower file size and all that stuff...
I am using mingw(32 bit) gnu assembly on windows 7
Yes, Linker combines all the .o files (built from .s files) and makes a single object file. So all your c files will first become assembly files.
Each assembly file will have an import list, and an export list. Export list contains all the variables that have a .global
or .globl
directive. Import list contains all the variables that start with a extern in the c file. (GAS, unlike NASM, doesn't require declaring imports, though. All symbols that aren't defined in the file are assumed to be external. But the resulting .o
or .obj
object files will have import lists of symbols they use, and require to be defined somewhere else.)
So if your assembly file contains this:
.globl _num # _num is a global symbol, when it is defined
.data # switch to read-write data section
.align 4
_num: # declare the label
.long 33 # 4 bytes of initialized storage after the label
All you need to do in order to use num, is to create a extern variable like this
extern int num; // declare the num variable as extern in your C code
and then you'll be able to read it or modify it.
Many platforms (Windows, OS X) add a leading underscore to symbol names, so the C variable num
has an asm name of _num
. Linux/ELF doesn't do this, so the asm name would also be num
.
Yes, you can share variables both ways. use the .globl as you have and then in C declare an external variable as if it were in another C module but instead it is in an asm module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With