I have a Qt GUI application running on Windows that allows command-line options to be passed and under some circumstances I want to output a message to the console and then quit, for example:
int main(int argc, char *argv[]) { QApplication a(argc, argv); if (someCommandLineParam) { std::cout << "Hello, world!"; return 0; } MainWindow w; w.show(); return a.exec(); }
However, the console messages do not appear when I run the app from a command-prompt. Does anyone know how I can get this to work?
Qt is a cross-platform application and graphical user interface (GUI) framework, a toolkit, that is used for developing software that can be run on different hardware platforms and operating systems.
Windows does not really support dual mode applications.
To see console output you need to create a console application
CONFIG += console
However, if you double click on the program to start the GUI mode version then you will get a console window appearing, which is probably not what you want. To prevent the console window appearing you have to create a GUI mode application in which case you get no output in the console.
One idea may be to create a second small application which is a console application and provides the output. This can call the second one to do the work.
Or you could put all the functionality in a DLL then create two versions of the .exe file which have very simple main functions which call into the DLL. One is for the GUI and one is for the console.
Add:
#ifdef _WIN32 if (AttachConsole(ATTACH_PARENT_PROCESS)) { freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } #endif
at the top of main()
. This will enable output to the console only if the program is started in a console, and won't pop up a console window in other situations. If you want to create a console window to display messages when you run the app outside a console you can change the condition to:
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With