Assembly with C++

I made a little test today in order to understand how to implement some ASM code inside a C++ program. It works as expected. However I notice that at end I have as a final output code : 1 instead of 0. There is something wrong here. I missed something so as to quit properly this process?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <Windows.h>
#include <string>

int main()
{
    auto msg = R"(Hello World)"; // message
    auto cpt = R"(Test)";        // caption

    _asm
    {
	mov eax, 0
	mov ebx, cpt
	mov ecx, msg
	mov edx, 0

	push eax
	push ebx
	push ecx
	push edx
	call MessageBoxA

	leave
	ret
    }

    return 0;
}
Last edited on
I would think the return value is in eax, and was probably last set by MessageBoxA.
Why have leave/ret? That terminates the program and hence return 0 isn't executed.

If you want to return from within the asm code then you need to set eax to 0 (or other required return code) before the exit.

However, why not just exit via the return?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX

#include <Windows.h>
#include <string>
#include <iostream>

int main() {
	auto msg = R"(Hello World)"; // message
	auto cpt = R"(Test)";        // caption

	_asm
	{
		mov eax, 0
		mov ebx, cpt
		mov ecx, msg
		mov edx, 0

		push eax
		push ebx
		push ecx
		push edx
		call MessageBoxA
	}

	std::cout << "Exiting\n";

	return 0;
}



Note that in-line assembler can only be used with a 32 bit build. You can't do this with a 64-bit build.
Last edited on
For an unknown reason, my previous code (without leave ret) works as expected without any bad output code. I don't know what it means. Sometimes...
Strange. Thank you for your help ++
Last edited on
I don't know what it means.


Definitely a lack of coffee...
I think unless the function is declared with __attribute__((naked)), the compiler generates the "prologue" and "epilogue" for you. By returning from in-line assembly, wouldn't you skip the "epilogue"?
Last edited on
Topic archived. No new replies allowed.