Opening console from WinAPI gui program on mingw:

2019-05-31 17:09发布

问题:

I am currently working on WinAPI Gui application under MinGW. In debug version I want to open console and redirect stdin/stdout streams to it, so I can see diagnostic messages being printed in debug. I followed this article: http://justcheckingonall.wordpress.com/2008/08/29/console-window-win32-app/

It works under Visual Studio, but when compiled on MinGW it spits this message, even if stdio.h is included:

error: '_fdopen' was not declared in this scope

Arguments for MinGW:

mingw32-g++.exe -march=pentium4 -std=c++11 -w -fpermissive -fno-strict-aliasing -D__STDC_CONSTANT_MACROS -D_WINDOWS -DUNICODE -D_UNICODE -g -D_DEBUG

I've googled a lot and it seems to be a bug in MinGW, there is no _fdopen defined in header if C++11 is used. Since I rely on C++11 features, I cannot turn it off, so I am looking for alternatives - is there any way to open console on Windows and redirect stdin/stdout that does not rely on fdopen? If not, are there any other solutions to my problem?

I tried also to manually declare _fdopen (or fdopen), but then it didn't pass the linking phase

MinGW version: 4.7.1

回答1:

From some brief research, it is my understanding that you should be able to use _fdopen/fdopen in GNU C++11 with the right configuration settings (i.e., by enabling POSIX functions) but that there is a long-standing bug in the Windows implementations. Whether you can directly work around this issue presumably depends on which runtime library you're using.

However, there are various other potential workarounds depending on the scenario:

  • In your particular case, since you're making the decision at build time, you can simply build the debug version as a console application and let Windows do the work.

  • It should be possible (again, depending on the runtime library) to configure the build so that some code of yours runs before the runtime library initialization; hopefully, if the console is already present the runtime library will import the standard streams during initialization.

  • You should be able to open CONIN$ and/or CONOUT$ using fopen so as to obtain FILE objects directly, rather than using GetStdHandle to obtain Windows handles. This is probably the most general solution.