Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two small files that I want to compile in CMake for debugging it with CLion and GDB

main.c

int my_strlen(char *);

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

and I have my ASM file that have a my_strlen file

    [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

I'm trying to compile with a CMakeList.txt I add set_source_files_properties but it still doesn't work

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)

Someone knows a good command to add ASM file in a C project and compile with a CMakeList.txt ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

You'll probably have to enable NASM support in CMAKE with enable_language(ASM_NASM)and then set appropriate assembly options:

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)

Since your code seems to be a 64-bit target I essentially pass -f elf64 as a command line option to NASM. I place the format type in its own environment variable CMAKE_ASM_NASM_OBJECT_FORMAT. To enable debug information in NASM you can use the -g -Fdwarf.


If doing Debug and Release builds you could check for the build type and set the flags accordingly with something like:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...