I’m teaching myself Intel x64 assembler with the assistance of a really good textbook: “The Art of 64-Bit Assembly” by Randall Hyde. I’ve run into a snag trying to call the C/C++ printf function from a MASM program. (I’m running MASM Version 14.39.33523.0 in Visual Studio 2022 (64-bit) Version 17.9.6 on a Windows 10 64-bit platform.) The program assembles successfully, but generates a link error on the CALL PRINTF instruction. Here’s the program:
; Test Call C++ Function printf()
; testPrintf.asm
option casemap:none ; Establish case sensitivity for compatibility with C/C++
includelib kernel32.lib
nl = 10 ; ASCII code for newline
.data
prtStr byte "Hello, World!", nl, 0
.code
externdef printf:proc ; External declaration for C/C++ printf() function
public asmMain
asmMain proc
sub rsp, 56 ; Set aside space for shadow registers, etc.
lea rcx, prtStr
call printf
add rsp, 56 ; Pop off space for shadow registers, etc.
ret
asmMain endp
end
From VS Command Line after running vcvars64.bat:
ml64 testPrintf.asm /link /subsystem:console /entry:asmMain
Link Errors:
testPrintf.obj : error LNK2019: unresolved external symbol printf referenced in function asmMain
testPrintf.exe : fatal error LNK1120: 1 unresolved externals
I’ve tried a few other ways to perform the call that I found on this forum (and others), but I haven’t found a solution that doesn’t produce these link errors. I think I may need to add an INCLUDELIB statement, but I also can’t find the name of the library that contains the printf function.
It’s a bit maddening because it seems like a problem that should be relatively easy to fix, but the solution eludes me despite several hours of research and trial-and-error. If you see the problem, your assistance would be greatly appreciated. Thank you.
Tried:
- Using extern instead of externdef.
- Declaring and linking to __imp_printf instead of printf. This worked for a couple of other C/C++ functions, but not for printf.
- Searching for and reading questions that matched with terms like “MASM”, “LINK ERROR”, “Call C/C++ PRINTF”, etc.
- Searching the Visual Studio user forums.
- Guessing at INCLUDELIB names likely to contain printf (couldn’t find that, either)
- Pleading, groveling, crying, begging, conniving, promising, threatening, doodling exploding heads, binge-eating hot pockets. Nothing worked.