.386
.model flat, c
.stack 100h
printf PROTO arg1:Ptr Byte
.data
msg1 byte "Hello World!", 0Ah, 0
.code
main proc
INVOKE printf, ADDR msg1
ret
main endp
end main
Hi, I am getting the below errors:
I searched around and found someone said that it can be fixed by linking the microsoft runtime library
Can anyone teach me how can I exactly fix it?
Thanks
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol _printf referenced in function _main testing C:\Users\Kin\Desktop\assembly\testing\testing\Source.obj 1
Error LNK1120 1 unresolved externals testing C:\Users\Kin\Desktop\assembly\testing\Debug\testing.exe 1
I don't have VS 2017 installed to try this. Important: Make sure you create a Console Application
and not a Windows Application
. Once you create this project make sure MASM is added to the build customizations. Add an .ASM
file to your project.
Take your code and insert the following lines at the top:
includelib libcmt.lib
includelib libvcruntime.lib
includelib libucrt.lib
includelib legacy_stdio_definitions.lib
An explanation as to why these lines are needed in Visual Studio later than 2013 can be found in this Stackoverflow Answer.
You want the C runtime to be the entry point to your console application (which in turn will call your main
). Because of this you MUST remove main
from the last line that says end main
. When you do end main
it bypasses the C runtime startup startup. Failure to properly initialize the C runtime will likely lead to the program crashing when you make calls like printf
. It should simply be end
and not end main
.
The final code you should test is:
includelib libcmt.lib
includelib libvcruntime.lib
includelib libucrt.lib
includelib legacy_stdio_definitions.lib
.386
.model flat, c
.stack 100h
printf PROTO arg1:Ptr Byte
.data
msg1 byte "Hello World!", 0Ah, 0
.code
main proc
INVOKE printf, ADDR msg1
ret
main endp
end
Since Visual Studio 2015, printf is now "inlined" into C code. The assembly code to get around this would be complicated. I ended up including a small C source file in the project with a unused call to printf to get around this problem. I don't recall if the generated printf code is parameter count dependent. I just use the same or more parameters in the dummy C source code call to printf than what I use in the assembly code.