Search code examples
c++assemblygccinline-assembly

is it possible to define a full assembly function in a c++ file


i use vscode with gcc on windows. i know that it is possible to write a c++ function and use asm("code"), however i came accross the following yt video:https://www.youtube.com/watch?v=7Xe9pCrzH98 where the author showcases the following c++ code:

__asm int sum4(int a,int b,int c,int d){
PUSH {r4, lr}
MOV r4, r0
ADD r4, r4, r1
ADD r4, r4, r2
ADD r0, r4, r3
POP {r4, pc}
}

which defines an entire asm function, instead of defining a c++ function with inside it the asm keyword, however i have not been able to replicate this. is it possible and does it even make a difference? i would imagine the compiler might add things for a c++ function

extern "C" int ret100(void);
__asm(
"ret100:\n"
"  mov $100,%rax\n"
"  ret\n"
);

works so i tried various variations of

__asm int ret100(){
"mov $100,%rax\n"
"ret"
}

to no avail

edit: solution: i dont know if it is still possible to define a full asm function, however you can make the function naked, which means it doesnt create a pro and -epilogue, this can be done with __delspec( naked ) and thus the following function:__declspec( naked ) int ret100(void){asm("mov $100, %eax\nret\n");} creates an asm function with only the two asm statements in the body. credit to Jester

naked function wiki:learn.microsoft.com/en-us/cpp/cpp/naked-cpp?


Solution

  • You want a naked function, e.g.:

    __attribute__((naked))
    int ret100(void)
    {
        __asm__(
            "mov $100, %eax\n"
            "ret\n"
        );
    }