assembly C++文件无法识别程序集文件中定义的函数

hl0ma9xz  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(109)

我正在尝试学习一些汇编代码,我正在遵循一本书中提出的教程,我得到了一个C++代码,定义如下(Ch02_01.cpp):

#include <iostream>

using namespace std;

extern "C" int IntegerAddSub_(int a, int b, int c, int d);
int main() {
    int a, b, c, d, result;
    a = 101;  b = 34; c = -190; d = 25;
    result = IntegerAddSub_(a, b, c, d);
    cout << "result = " << result << n1;
    return 0;
}

已知函数IntegerAddSub_是在文件夹中的组件文件(扩展名为asm)中定义的,如下所示(Ch02_01.asm):

; extern "C" int IntegerAddSub_(int a, int b, int c, int d);

        .code
IntegerAddSub_ proc
; Calculate a + b + c -d
        mov eax, ecx      ;eax = a
        add eax, edx      ;eax = a + b
        add eax, r8d      ;eax = a + b + c
        sub eax, r9d      ;eax = a + b + c - d
        ret               ; return result to caller

IntegerAddSub_ endp
        end

错误消息:

Error message :
/home/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/222.3345.126/bin/cmake/linux/bin/cmake --build /home/Assembly/cmake-build-debug --target Assembly -j 16
[1/1] Linking CXX executable Assembly
FAILED: Assembly 
: && /usr/bin/c++ -g  CMakeFiles/Assembly.dir/Ch02_01.cpp.o -o Assembly   && :
/usr/bin/ld: CMakeFiles/Assembly.dir/Ch02_01.cpp.o: in function `main':
/home/Assembly/Ch02_01.cpp:25: undefined reference to `IntegerAddSub_'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

我认为错误的语义很简单,C++文件没有识别汇编程序文件中定义的函数。
根据评论中的交流,我将补充以下信息:我正在使用CLION(来自Jetbrains),这是我的CMakeLists.txt

cmake_minimum_required(VERSION 3.23)
project(Assembly)

set(CMAKE_CXX_STANDARD 14)
set ( SOURCES
      Ch02_01.asm
    )
add_executable(Assembly
        Ch02_01.cpp)

我不知道如何用g++编译,它从来不识别ASM文件中的函数,请问我如何才能成功编译?我在Ubuntu中。谢谢

1wnzp6jl

1wnzp6jl1#

您需要告诉CMake该项目也包含nasm代码-或者masm(如果它实际上是masm)。
示例:

cmake_minimum_required(VERSION 3.22)
project(Assembly CXX ASM_NASM) # or perhaps it should be ASM_MASM

set(CMAKE_CXX_STANDARD 14)

add_executable(Assembly Ch02_01.asm Ch02_01.cpp)

这使得它至少可以尝试编译asm文件,但对我来说,它失败了:

[ 33%] Building ASM_NASM object CMakeFiles/Assembly.dir/Ch02_01.asm.o
/home/ted/proj/stackoverflow/assembly/Ch02_01.asm:3: warning: label alone on a line without a colon might be in error [-w+label-orphan]
/home/ted/proj/stackoverflow/assembly/Ch02_01.asm:4: error: parser: instruction expected
/home/ted/proj/stackoverflow/assembly/Ch02_01.asm:12: error: label `IntegerAddSub_' inconsistently redefined
/home/ted/proj/stackoverflow/assembly/Ch02_01.asm:4: info: label `IntegerAddSub_' originally defined here
/home/ted/proj/stackoverflow/assembly/Ch02_01.asm:12: error: parser: instruction expected
/home/ted/proj/stackoverflow/assembly/Ch02_01.asm:13: warning: label alone on a line without a colon might be in error [-w+label-orphan]
make[2]: *** [CMakeFiles/Assembly.dir/build.make:76: CMakeFiles/Assembly.dir/Ch02_01.asm.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/Assembly.dir/all] Error 2
make: *** [Makefile:91: all] Error 2

相关问题