Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access variables defined in assembly from C?

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

like image 476
orustammanapov Avatar asked Mar 11 '12 22:03

orustammanapov


2 Answers

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.

like image 105
theRealWorld Avatar answered Nov 15 '22 07:11

theRealWorld


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.

like image 24
old_timer Avatar answered Nov 15 '22 06:11

old_timer