Simple Assembly program on visual studio 2017

kireinasora picture kireinasora · May 20, 2017 · Viewed 7k times · Source
        .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   

Answer

Michael Petch picture Michael Petch · May 20, 2017

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