Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Good Old & Dirty printf() Debugging in a Non-console C/C++ Application or DLL

5.00/5 (11 votes)
25 Jul 2012CPOL1 min read 43.3K  
How to open a console in a non-console C/C++ application or DLL and make printf/scanf work (stdin/stdout/stderr related functions)

Introduction

Don't expect magic, and your dreams coming true by reading this short and dirty hack. Still this tip serves the answer to a question that I sometimes see here and there on the forums. As the subtitle says, this hack opens a console window in an application that otherwise doesn't have one, and makes printf()/scanf() and other <stdio.h> related functions work! I know that sophisticated programs use logging systems, so use that if you have one. I used this solution only once, when I wrote an injectable DLL (w-mode) that was injected into a game (starcraft), and I wanted the DLL to open a console window inside the guest process for logging. I did this in C++ only in debug builds, and used some logging macros that were preprocessed to printf() in debug mode and to nothing in release mode. That time, I used Visual C++ 6, but I tested it with Visual C++ 2005 and 2008 as well and it worked. So here is the code:

C++
AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
You should put this somewhere to the beginning of the entrypoint function of your application or DLL (in your WinMain() or DllMain()). And my debug macros for newer (.NET) Visual Studio versions that support vararg macros:
C++
#ifdef _DEBUG
# define Debug(fmtstr, ...) printf(fmtstr, ##__VA_ARGS__)
#else
# define Debug(fmtstr, ...)
#endif

Put the above code to a global place, for example to your stdafx.h.

You could achieve the same by logging into a file, and by using a log watcher program that has its window open all the time and detects your logfile recreations/appendings like "tail -f" command of a linux/cygwin. Still, if you don't have a nice log watcher program or you just want to log out something in guest code and then undo your changes, this dirty hack might do the job.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)