[英]What is the correct way to link assembly code with C code using gcc
假設您具有以下程序集文件:
.file "print.s"
.intel_syntax noprefix
.text
.globl _start
.type _start, @function
_start:
mov rax, 1
mov rdi, 1
lea rsi, hello_string
mov rdx, 14
syscall
mov rax, 60
mov rdi, 0
syscall
.size _start, .-_start
和
.file "string.s"
.intel_syntax noprefix
.data
.globl hello_string
.type hello_string, @object
hello_string:
.string "Hello, world!\n"
.size hello_string, 14
如果您as string.s -o string.o
as print.s -o print.o
運行, as print.s -o print.o
,然后以ld *.o -o hello.elf
,您將獲得一個可執行文件,該文件顯示Hello,world!。 現在,假設您將print.s中的_start
標簽更改為print
並且具有以下C文件:
// main.c
void print(void);
int main (void) {
print();
return 0;
}
我想運行gcc -o main.elf main.c string.s print.s
以獲取我的兩個程序集文件並將它們鏈接到標准C運行時中。 編寫的此命令無效。 我收到以下錯誤消息:
/usr/bin/ld: /tmp/ccc1yRif.o: relocation R_X86_64_32S against symbol `hello_string' can not be used when making a shared object; recompile with -fPIC
我無法弄清楚如何正確使用-fPIC標志使事情正常進行。 我什至不確定那是我應該做的。 我可以嘗試使用內聯匯編器執行此操作,但是對於我的實際用例而言,這將非常煩人,而我寧願學習如何將匯編塊正確鏈接到C程序中。 我目前無法在網上找到太多信息。
問題:如何正確使用GNU鏈接器將程序集文件鏈接到C運行時?
編輯:在如何將C對象文件與匯編語言對象文件鏈接? ,OP正在詢問如何僅使用ld
解決類似的鏈接問題。 我想使用gcc
,這是鏈接問題中的推薦解決方案,但我什至無法使它起作用。
好,所以我現在想通了。 錯誤消息似乎告訴我gcc正在嘗試創建共享對象。 這使我想到gcc 6.2.0是否在不應該嘗試創建共享庫的問題?
解決方案是運行gcc -no-pie main.c string.s print.s -o main.elf
根據手冊頁, -no-pie
告訴gcc不產生位置獨立的可執行文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.