問題描述
如何使用 Assembly 中的 printf? (How do you use printf from Assembly?)
I have an MSVC++ project set up to compile and run assembly code.
In main.c:
#include <stdio.h>
void go() ;
int main()
{
go() ; // call the asm routine
}
In go.asm:
.586
.model flat, c
.code
go PROC
invoke puts,"hi"
RET
go ENDP
end
But when I compile and run, I get an error in go.asm:
error A2006: undefined symbol : puts
How do I define the symbols in <stdio.h>
for the .asm files in the project?
‑‑‑‑‑
參考解法
方法 1:
Here's what I have.
It works!!
.586 .model flat,c printf PROTO C :VARARG ; The secret sauce.. a prototype of printf .data msgHello1 BYTE "GREETINGS AND WELCOME TO EARTH!",0 .code go PROC push OFFSET msgHello1 call printf add esp, 4 ; Stack cleaning RET go ENDP end
- "stack cleaning"
- How to call variadic argument function such as printf
方法 2:
I think this article explains it better than I can.
Roughly put, the assembler cannot find the symbol (function) in go.asm
. You have to tell it its an external symbol.
The linked article approaches building a mixed‑code app from the point of view of using assembly as the main language including running the main
routine. If you're using a C
based main routine, much of what is done is unnecessary, you should just need:
Assemble the assembly module with /Mx to preserve the case of nonlocal names. If using MASM version 6.0 or later, use /Cx to preserve the case of nonlocal names.
and:
Include the statement .MODEL , c in the assembly module to ensure that C naming and calling conventions are used and that the modules use the same default segments. The will be small, medium, compact, or large.
and EXTERN
directives for each function you wish to call in the format: EXTERN printf:proc
.
(by bobobobo、bobobobo、user257111)