简体   繁体   中英

Combining c and assembler code

This is my C code:

#include <stdio.h>

    void sum();
    int newAlphabet;
    int main(void)
    {
        sum();
        printf("%d\n",newAlphabet);
    }

And this is my assembler code:

.globl _sum

_sum:
    movq $1, %rax
    movq %rax, _newAlphabet
    ret

I'm trying to call the sum function, from my main function, to set newAlphabet equal to 1, but when I compile it ( gcc -o test assembler.c assembler.s , compiled on a 64-bit OSX laptop) I get the following errors:

32-bit absolute addressing is not supported for x86-64

cannot do signed 4 byte relocation

both caused by the line "movq %rax, _newAlphabet"

I'm sure I'm making a very basic mistake. Can anyone help? Thanks in advance.

EDIT:

Here are the relevant portions of the C code once it has been translated to assembler:

.comm   _newAlphabet,4,2
...
movq    _newAlphabet@GOTPCREL(%rip), %rax

Mac OS X uses position-independent executables by default, which means your code can't use constant global addresses for variables. Instead you'll need to access globals in an IP-relative way. Just change:

movq %rax, _newAlphabet

to:

mov %eax, _newAlphabet(%rip)

and you'll be set (I changed from 64 to 32 bit registers to match sizeof(int) on Mac OS X. Note that you also need a .globl _newAlphabet in there somewhere. Here's an example I just made based on your code (note that I initialized newAlphabet to prove it works):

example.c:

#include <stdio.h>

void sum(void);
int newAlphabet = 2;
int main(void)
{
    printf("%d\n",newAlphabet);
    sum();
    printf("%d\n",newAlphabet);
    return 0;
}

assembly.s:

.globl _sum
.globl _newAlphabet

_sum:
    movl $1, _newAlphabet(%rip)
    ret

Build & run:

$ cc -c -o example.o example.c
$ cc -c -o assembly.o assembly.s
$ cc -o example example.o assembly.o
$ ./example
2
1

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