簡體   English   中英

混合c和組裝。 在終端上什么也沒印

[英]mixing c and assembly. On the terminal nothing printed

我在這里寫的是一個簡單的代碼:

 printf.asm

 [EXTERN main]
 section .text
 global _start     
 _start:
       call main
       add esp, 8
       mov eax, 1
       xor ebx, ebx
       int 80h

和main.c

#include <stdio.h>

 int main()
 {
     char* str = "print from C :\\)";
     printf("%s", str);
 }

我這樣編譯代碼:

nasm -g -f elf printf.asm -o printf.o

gcc -c -o main.o main.c

ld -o printf printf.o main.o -lc -I/lib/ld-linux.so.2

並運行:

./printf

在終端上沒有任何打印內容。 為什么呢

當我使用以下命令ld -Ttext 0x1000 -o printf printf.o main.o -lc -I/lib/ld-linux.so.2進行鏈接時,它顯示“殺死”字符串。 如何解決這個問題呢 ?

只需在printf函數中添加換行符即可成功獲得代碼: printf("%s\\n", str); 謝謝,問題已經解決。

您試圖先不執行C啟動代碼就調用main()。 你不應該那樣做。 基本上,C啟動會在跳轉到main()之前初始化堆棧和變量存儲。

您可以從main()調用匯編語言代碼,因為這允許啟動程序先執行其操作。

您正在編寫_start自己,這是一個libc啟動函數。這是無法正確鏈接代碼的原因。也不要觸摸_start,否則會破壞libc。 要在main之前運行代碼,可以使用`` attribute ((constructor))''(這是gcc功能,在其他編譯器中不可用)。

具有NASM-entrypoint的混合源以這種方式工作(在我的64位Linux上為32位):

printf.asm:

global _start
extern main
extern fflush

section .text
 _start:
    call main

    push 0                      ; fflush (stdout)
    call fflush
    add esp, 4

    mov ebx,0                   ; exit code, 0=normal
    mov eax,1                   ; exit command to kernel
    int 0x80                    ; interrupt 80 hex, call kernel

main.c

#include <stdio.h>

extern int main (void)
{
    char* str = "print from C :\\)\n";
    printf("%s", str);
    return 0;
}

建立:

nasm -felf32 -oprintf.o printf.asm
gcc -c -m32 -omain.o main.c
ld -I/lib32/ld-linux.so.2 -lc -m elf_i386 -o printf printf.o main.o

我想您可以管理32位Linux的更改:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM