簡體   English   中英

如何將混合(asm,C ++)源代碼編譯為32位程序?

[英]How can I compile a hybrid (asm, C++) source code into a 32-bit program?

我在64位計算機上的Win7下使用32位Cygwin

以下程序

生成文件:

runme:  main.cpp    asm.o
        g++ main.cpp    asm.o   -o  executable

asm.o:  asm.asm
        nasm    -f  elf     asm.asm     -o  asm.o 

asm.asm:

section .data
section .bss
section .text
    global GetValueFromASM

GetValueFromASM:
    mov eax, 9
    ret

main.cpp:

#include <iostream>

using namespace std;

extern "C" int GetValueFromASM();

int main()
{
    cout<<"GetValueFromASM() returned = "<<GetValueFromASM()<<endl;

    return 0;
} 

給我以下錯誤:

$ make
nasm    -f      elf             asm.asm         -o      asm.o
g++     main.cpp        asm.o   -o      executable
/tmp/cc3F1pPh.o:main.cpp:(.text+0x26): undefined reference to `GetValueFromASM'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: runme] Error 1

我不明白為什么會產生此錯誤。

我如何擺脫這個問題?

您必須在符號前面加上_ ,這在Windows / Cygwin中是慣用的:

section .data
section .bss
section .text
    global _GetValueFromASM

_GetValueFromASM:
    mov eax, 9
    ret

您的其余代碼應該可以正常工作。

一種替代方法是使用-fno-leading-underscore進行編譯。 但是,這可能會中斷與其他(Cygwin系統)庫的鏈接。 如果對其他平台的可移植性無關緊要,我建議使用第一種方法。

引用GNU在線文檔:

-fleading-underscore

此選項及其對應的-fno-leading-underscore強制更改目標文件中C符號的表示方式。 一種用途是幫助鏈接舊的匯編代碼。

警告: -fleading-underscore開關使GCC生成的代碼與沒有該開關的代碼不二進制兼容。 使用它來符合非默認應用程序二進制接口。 並非所有目標都為此開關提供完全支持。

暫無
暫無

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

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