简体   繁体   中英

Using global variables declared in C, in Arm assembly

I have a C file which declares a global variables. This file will be compiled together with some ARM assembly files.

int foo;

void call_asm(void);

int main(void) {
    call_asm();
    return foo;
}
call_asm:
    ...

I tried using the link from the arm infocenter but the compiler ( arm-linux-gnueabi-gcc ) is telling me that "import" is an undefined instruction.

Can I simply do something like:

LDR    r0, =GLOBAL_VAR

How can I use the global variables defined in the C file in assembly?

This becomes quite simple once you ask gcc how to do it. For example, compile the following function with gcc -S -O3 :

extern int foo;
void useFoo()
{
    foo=7;
}

You'll see how gcc implements it.

Based on this, I've devised a working example of calling an assembly function from C to set a global C variable:

// test.c
#include <stdio.h>

void setupFoo();
int foo;

int main()
{
    setupFoo();
    printf("foo=%d\n", foo);
}
# test.s
.text
.global foo
.fooAddr:
    .word foo

.global setupFoo
setupFoo:
    ldr r0, .fooAddr
    mov r1, #123
    str r1, [r0]
    bx lr

Compilation and running:

$ gcc test.c test.s -o test && ./test
foo=123

Tested on gcc Raspbian 6.3.0-18+rpi1.

That assembly code above was based on the gcc output for the useFoo example. A simpler way is to use =foo instead of manually placing the address to a variable:

# test.s
.text
.global foo
.global setupFoo
setupFoo:
    ldr r0, =foo
    mov r1, #123
    str r1, [r0]
    bx lr

This will result in the address of foo being put after the function definition by the assembler.

I think you need to translate the directives from the ARM assembler to the GNU assembler. If I understand correctly, you can access any global symbol by using the .global directive instead of .import . From the Using as pages:

.global symbol

.global makes the symbol visible to ld. If you define symbol in your partial program, its value is made available to other partial programs that are linked with it. Otherwise, symbol takes its attributes from a symbol of the same name from another file linked into the same program.

.extern (symbol)

是你需要的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM