2013-05-25 36 views
0

我使用包含C語言和混合代碼的混合代碼在引導加載程序上創建簡單的計算器應用程序。使用混合代碼使用EXTERN的引導加載程序

我的C語言代碼(addasm.c): 的#include

 int main() { 

bootmain(); 
return 0 ; 

    } 
    int bootmain() 
    { 
int arg1, arg2, add, sub, mul, quo, rem ; 

printf("Enter two integer numbers : "); 
scanf("%d%d", &arg1, &arg2); 

/* Perform Addition, Subtraction, Multiplication & Division */ 
__asm__ ("addl %%ebx, %%eax;" : "=a" (add) : "a" (arg1) , "b" (arg2)); 
__asm__ ("subl %%ebx, %%eax;" : "=a" (sub) : "a" (arg1) , "b" (arg2)); 
__asm__ ("imull %%ebx, %%eax;" : "=a" (mul) : "a" (arg1) , "b" (arg2)); 

__asm__ ("movl $0x0, %%edx;" 
      "movl %2, %%eax;" 
      "movl %3, %%ebx;" 
      "idivl %%ebx;" : "=a" (quo), "=d" (rem) : "g" (arg1), "g" (arg2)); 

printf("%d + %d = %d\n", arg1, arg2, add); 
printf("%d - %d = %d\n", arg1, arg2, sub); 
printf("%d * %d = %d\n", arg1, arg2, mul); 
printf("%d/%d = %d\n", arg1, arg2, quo); 
printf("%d %% %d = %d\n", arg1, arg2, rem); 
return 0; 
} 

我創造了用C,我需要在彙編代碼使用bootmain()函數。

我的彙編代碼(ccode.asm)是:

[BITS 16] ; 16 bit code generation 
[ORG 0x7C00] ; ORGin location is 7C00 
extern bootmain 

    ;Main program 
    main:  ; Main program label 

    call bootmain 

    ; End matter 
    times 510-($-$$) db 0 ; Fill the rest of the sector with zeros 
    dw 0xAA55  ; Boot signature 

現在我編寫本

nasm -f elf -o main.o ccode.asm #assemble our asm file 

,但它給了我錯誤ORG關鍵字,這是不確定的關鍵字。

如果我將刪除這個關鍵字,那麼它會給我錯誤的輸出。

移除ORG關鍵字之後,我像編譯這樣:

nasm -f elf -o main.o ccode.asm #assemble our asm file 
    gcc addasm.c main.o -o add_asm  #compile and link in one step 
    ./add_asm      

所以我用這最後add_asm文件,並通過puting使用磁盤Explorer,這add_asm文件讓我的USB驅動器引導。 但在啓動它顯示消息:操作系統丟失 所以這是一個在彙編文件中不使用ORG的問題。 這主要是ELF的問題,我正在使用NASM.But爲外部C函數和EXTERN關鍵字我需要使用ELF。

ORG的替代代碼:

[Bits 16] 
    extern bootmain 
    start: 
    mov ax, 07C0h ; Set up 4K stack space after this bootloader 
    add ax, 288 ; (4096 + 512)/16 bytes per paragraph 
    mov ss, ax 
    mov sp, 4096 
call bootmain 
mov ax, 07C0h ; Set data segment to where we're loaded 
mov ds, ax 
times 510-($-$$) db 0; Pad remainder of boot sector with 0s 
dw 0xAA55 ; The standard PC boot signature 

但它也不起作用......它給了我同樣的錯誤「丟失操作系統」,在開機的時間。

是否有任何其他方式將C函數包含在程序集文件(* .asm)中? 我被困在這裏。如果有任何建議,請給我。 謝謝。

回答

0

你不能把一個普通的C程序變成一個像這樣的bootloader。

  • 引導加載程序運行的環境與正常的可執行程序明顯不同。尤其是,它不包含可以鏈接到的C庫(或者就此而言,任何鏈接器!),因此printf()scanf()之類的函數不可用,除非您鏈接了適當的版本,而您並未執行此操作。

  • 您正在將您的程序編譯爲32位可執行文件。一個x86系統以16位模式啓動。必須進行大量的初始化才能切換到該模式,這裏沒有一個出現。

  • 您正在將您的程序編譯爲Linux ELF(或可能是Windows PE?)可執行文件。這不是引導加載程序的正確格式。

+0

是否有任何其他方式在程序集文件(* .asm)中包含C函數? – SNC

+0

以及如何在asm中使用nasm編譯c文件和asm文件? – SNC

+0

你似乎很困惑。 NASM不是C編譯器。它無法編譯或包含C源文件。結合編譯的C和ASM文件是鏈接器的工作,而不是NASM。 – duskwuff

相關問題