[英]Combining c and assembler code
這是我的C代碼:
#include <stdio.h>
void sum();
int newAlphabet;
int main(void)
{
sum();
printf("%d\n",newAlphabet);
}
這是我的匯編代碼:
.globl _sum
_sum:
movq $1, %rax
movq %rax, _newAlphabet
ret
我試圖從主函數調用sum函數,將newAlphabet
設置為1,但是當我編譯它( gcc -o test assembler.c assembler.s
,在64位OSX便攜式計算機上編譯)時,我得到了以下錯誤:
32-bit absolute addressing is not supported for x86-64 cannot do signed 4 byte relocation both caused by the line "movq %rax, _newAlphabet"
我確定我犯了一個非常基本的錯誤。 有人可以幫忙嗎? 提前致謝。
編輯:
一旦將C代碼轉換為匯編器,以下是它們的相關部分:
.comm _newAlphabet,4,2
...
movq _newAlphabet@GOTPCREL(%rip), %rax
Mac OS X默認情況下使用與位置無關的可執行文件,這意味着您的代碼不能對變量使用恆定的全局地址。 相反,您將需要以相對於IP的方式訪問全局變量。 只是改變:
movq %rax, _newAlphabet
至:
mov %eax, _newAlphabet(%rip)
並進行設置(我從64位寄存器更改為32位寄存器,以匹配Mac OS X上的sizeof(int)
。請注意,您還需要在其中添加.globl _newAlphabet
。這是我根據您的代碼制作的一個示例(請注意,我初始化了newAlphabet
以證明它可以工作):
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
構建並運行:
$ cc -c -o example.o example.c
$ cc -c -o assembly.o assembly.s
$ cc -o example example.o assembly.o
$ ./example
2
1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.