簡體   English   中英

直接在匯編中使用 stdlib.h 函數

[英]Using stdlib.h functions directly in assembly

我必須做一個匯編(x86)程序,它從用戶輸入中獲取 2 個長數字,使用 function 添加它們,然后打印結果。 當我使用 read 系統調用時,我得到一個 ASCII 十六進制代碼的字符串,我無法添加這樣的數字。 所以我想使用 atol 是 stdlib.h 的 function 將字符串轉換為長字符串。 如何在程序集中包含庫? 還有另一種方法可以做到這一點嗎?

我已經嘗試過:

  1. .file "stdlib.h" (我在當前目錄中有 lib)

錯誤:未定義對atol'

  1. 使用 clang 將 stdlib.h 與 .s 文件一起編譯

錯誤:stdlib.h:文件無法識別:文件格式無法識別

  1. 僅使用#include<stdlib.h>制作 a.c 文件並使用 .s 文件進行編譯

錯誤:未定義對“atol”的引用

我運行的 comads 是

clang function.s -c -g
ld function.o -o function

The linker complains that atol has not been found because it is a function in the C library, but you didn't tell the linker to add the C library to your program during linking. 要解決此問題,請將-lc傳遞給 linker 以在鏈接期間添加 C 庫:

ld -o function function.o -lc

-lc放在最后非常重要,否則鏈接可能不起作用。 這是因為 linker 按照您指定的順序從庫中選擇函數。 當您在function.o之前指定-lc時,它會忽略該庫,因為它現在不需要任何內容。 然后它看到function.o帶有未定義的atol並且沒有找到定義,導致鏈接失敗。

Lastly, when you use the C library, you should start your program from the main function (ie rename _start to main ) like a normal C program and link through the C compiler:

clang -g -o function function.s

這會導致 C 庫自動鏈接並正確初始化,防止出現一些奇怪的錯誤。 If you use any IO functions like printf from the C library, you should also end your program by calling exit so the standard IO streams are flushed correctly.

請注意, stdlib.h文件是一個紅鯡魚。 匯編編程不需要 Header 文件。 它們的目的是告訴 C 編譯器某些函數的類型是什么。 如果您不使用 C 編譯器,則不需要這樣做。 .file指令不符合您的預期。

您向項目添加了一個編譯單元(.c 文件)。 這里介紹了包含的header文件“stdlib.h”中的函數原型。 你想要的是參考那個 function。 這應該在使用 function 的匯編文件中引入。

extern語句添加到匯編程序文件應該可以完成這項工作。 您不需要包含包含的 C 文件。 您必須在 linker 設置中添加相應的庫。 但是即使你成功鏈接了一個 EXE 文件,你也可能會遇到問題,因為 stdlib 中的某些函數需要初始化。 您還必須調用 C 運行時初始化 function。

也許您可以使用extern ,例如: extern printfstdlib.h庫中您想要的任何內容

它適用於nasmmasm匯編程序。

暫無
暫無

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

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