使用ASM编译ASM和C以进行调试

时间:2018-03-06 13:28:41

标签: c assembly cmake nasm clion

我有两个小文件,我想在CMake中编译,以便用CLion和GDB进行调试

的main.c

int my_strlen(char *);

int main()
{
    printf("Test: %d\n", my_strlen("Hello"));
}

我的ASM文件有my_strlen文件

    [BITS 64]

    global my_strlen
    section .text

my_strlen:
    push rbp
    mov rbp, rsp
    xor rcx, rcx

loop:
    cmp BYTE [rdi + rcx], 0
    jz end
    inc rcx
    jmp loop

end:
    mov rax, rcx
    mov rsp, rbp
    leave
    ret

我正在尝试使用CMakeList.txt进行编译我添加了set_source_files_properties但它仍然无法正常工作

cmake_minimum_required(VERSION 3.9)
project(ASM)

set(CMAKE_CXX_STANDARD 11)
set_source_files_properties(src/strlen.asm PROPERTIES COMPILE_FLAGS "-x assembler-with-c")

add_executable(main
        src/strlen.asm
        tests/src/main.c)

有人知道在C项目中添加ASM文件并使用CMakeList.txt编译的好命令吗?

1 个答案:

答案 0 :(得分:5)

您可能必须使用enable_language(ASM_NASM)在CMAKE中启用NASM支持,然后设置适当的程序集选项:

cmake_minimum_required(VERSION 3.9)
project(ASM)
enable_language(ASM_NASM)
set(CMAKE_ASM_NASM_OBJECT_FORMAT elf64)
set(CMAKE_ASM_NASM_COMPILE_OBJECT "<CMAKE_ASM_NASM_COMPILER> <INCLUDES> \
    <FLAGS> -f ${CMAKE_ASM_NASM_OBJECT_FORMAT} -o <OBJECT> <SOURCE>")

set_source_files_properties(src/strlen.asm PROPERTIES COMPILE_FLAGS "-g -Fdwarf")

set(CMAKE_CXX_STANDARD 11)

add_executable(main
        src/strlen.asm
        tests/src/main.c)

由于您的代码似乎是64位目标,因此我基本上将-f elf64作为命令行选项传递给NASM。我将格式类型放在它自己的环境变量CMAKE_ASM_NASM_OBJECT_FORMAT中。要在NASM中启用调试信息,您可以使用-g -Fdwarf

如果执行Debug和Release构建,您可以检查构建类型并相应地设置标志,例如:

cmake_minimum_required(VERSION 3.9)
project(ASM)
enable_language(ASM_NASM)

set(CMAKE_ASM_NASM_OBJECT_FORMAT elf64)
set(CMAKE_ASM_NASM_COMPILE_OBJECT "<CMAKE_ASM_NASM_COMPILER> <INCLUDES> \
    <FLAGS> -f ${CMAKE_ASM_NASM_OBJECT_FORMAT} -o <OBJECT> <SOURCE>")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    set(CMAKE_ASM_NASM_FLAGS "${ASM_NASM_FLAGS} -g -Fdwarf")
else()
    set(CMAKE_ASM_NASM_FLAGS "${ASM_NASM_FLAGS}")
endif()

set(CMAKE_CXX_STANDARD 11)

add_executable(main
        src/strlen.asm
        tests/src/main.c)