Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Checking if running as command-line (QCoreApplication) or GUI
Qt 6.12 LTS is out! See what's new in the release blog

Checking if running as command-line (QCoreApplication) or GUI

Scheduled Pinned Locked Moved Unsolved General and Desktop
28 Posts 6 Posters 1.7k Views 4 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • PerdrixP Offline
    PerdrixP Offline
    Perdrix
    wrote last edited by
    #12

    The docs say nothing about undefined.

    1 Reply Last reply
    0
    • Christian EhrlicherC Offline
      Christian EhrlicherC Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote last edited by Christian Ehrlicher
      #13

      "only valid" = undefined if the precondition is not met.

      /edit:
      valid pointer - a pointer to an object which is not yet deleted and has the correct class
      invalid / not valid pointer - a pointer to an object which was already deleted or has an incorrect class
      nullptr - a pointer to null

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      1 Reply Last reply
      0
      • PerdrixP Offline
        PerdrixP Offline
        Perdrix
        wrote last edited by
        #14

        I still think the wording is open to my interpretation, however I have now defined my own convenience macro:

        //
        // Define a convenience macro for checking if we're using a Qt GUI or command line application
        // 
        #define qtGUI (dynamic_cast<QApplication *>(QCoreApplication::instance()))
        
        1 Reply Last reply
        0
        • JonBJ JonB

          @Perdrix
          I imagine that is a reasonable test if you want to do a Qt call, as in: "is there a QApplication object?"

          A global pointer referring to the unique application object. It is equivalent to QCoreApplication::instance(), but cast as a QApplication pointer, so only valid when the unique application object is a QApplication.

          However, are you intending to use single-source with two separate compilations/links, one for GUI and one for console? Because if you are thinking you can do just one compilation/link and decide at runtime whether to run as GUI or command line you are going to stall. Under Windows at least --- which ISTR you use --- an executable is linked as either "windows" (GUI) or "console" (command-line) and you are stuck with that at runtime.

          PerdrixP Offline
          PerdrixP Offline
          Perdrix
          wrote last edited by
          #15

          After further experiments this seems to be a non-starter. I wanted to use a message box for GUI and cout for command line, but of course the command line code isn't going to be linked with the libraries necessary to use QMessageBox.

          Hey ho! Compile time checks ...

          JonBJ 1 Reply Last reply
          0
          • PerdrixP Perdrix

            After further experiments this seems to be a non-starter. I wanted to use a message box for GUI and cout for command line, but of course the command line code isn't going to be linked with the libraries necessary to use QMessageBox.

            Hey ho! Compile time checks ...

            JonBJ Offline
            JonBJ Offline
            JonB
            wrote last edited by
            #16

            @Perdrix
            This is the sort of thing I was trying to discuss with you once you start trying to use qApp from a command-line executable.

            I wanted to use a message box for GUI and cout for command line, but of course the command line code isn't going to be linked with the libraries necessary to use QMessageBox.

            You implement this requirement via pointers-to-functions or subclassing-virtual-methods. It's a common paradigm. So that your code calls something like utilty.alert("Message") and that ends up calling either the GUI or the command-line implementation depending what function alert() pointer/virtual resolves to as set in construction/start-up. That keeps the command-line from needing to include/link with anything GUI.

            1 Reply Last reply
            0
            • PerdrixP Offline
              PerdrixP Offline
              Perdrix
              wrote last edited by
              #17

              Indeed so.

              JonBJ 1 Reply Last reply
              0
              • PerdrixP Perdrix

                Indeed so.

                JonBJ Offline
                JonBJ Offline
                JonB
                wrote last edited by JonB
                #18

                @Perdrix So you can do your "use a message box for GUI and cout for command line" if you wish. Just saying.

                1 Reply Last reply
                0
                • Pl45m4P Offline
                  Pl45m4P Offline
                  Pl45m4
                  wrote last edited by
                  #19

                  @Perdrix

                  What about this:

                  QCoreApplication* createApplication(int &argc, char *argv[])
                  {
                      for (int i = 1; i < argc; ++i) {
                          if (!qstrcmp(argv[i], "-no-gui"))
                              return new QCoreApplication(argc, argv);
                      }
                      return new QApplication(argc, argv);
                  }
                  
                  int main(int argc, char* argv[])
                  {
                      QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
                  
                      if (qobject_cast<QApplication *>(app.data())) {
                         // start GUI version...
                      } else {
                         // start non-GUI version...
                      }
                  
                      return app->exec();
                  }
                  

                  (from: https://doc.qt.io/qt-6/qapplication.html#details)


                  If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                  ~E. W. Dijkstra

                  JonBJ 1 Reply Last reply
                  0
                  • Pl45m4P Pl45m4

                    @Perdrix

                    What about this:

                    QCoreApplication* createApplication(int &argc, char *argv[])
                    {
                        for (int i = 1; i < argc; ++i) {
                            if (!qstrcmp(argv[i], "-no-gui"))
                                return new QCoreApplication(argc, argv);
                        }
                        return new QApplication(argc, argv);
                    }
                    
                    int main(int argc, char* argv[])
                    {
                        QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
                    
                        if (qobject_cast<QApplication *>(app.data())) {
                           // start GUI version...
                        } else {
                           // start non-GUI version...
                        }
                    
                        return app->exec();
                    }
                    

                    (from: https://doc.qt.io/qt-6/qapplication.html#details)

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote last edited by JonB
                    #20

                    @Pl45m4
                    Has anyone tried this, especially under Windows, to see what kind of "non-GUI version" you get? My understanding/suspicion is it will be a windows application (even if it opens no windows/widgets) which does not use/cannot access the console from which it is run, does not have open stdin/out/err and so on? Based on how MSVC non-Qt applications work.

                    Pl45m4P 1 Reply Last reply
                    0
                    • S Offline
                      S Offline
                      SimonSchroeder
                      wrote last edited by
                      #21

                      If I remember correctly, there are ways to reattach the console for a GUI application. I have found some old code of mine like this:

                      void openConsole()
                      {
                          AllocConsole();
                          std::freopen( "CON", "w", stdout );
                          std::freopen( "CON", "w", stderr );
                          std::freopen( "CON", "r", stdin );
                      }
                      

                      This function is called if the GUI application is started in non-GUI mode.

                      However, my solution for an app that works both as command line and GUI application on Windows is to compile two separate binaries. The GUI is the .exe file and the command line version is the .com file (command file). On the command line a .com file is preferred to a .exe file if you just type in the file name without the suffix. Also, I tend to make the non-GUI version the default because the GUI .exe is usually started through a shortcut and the shortcut can be set to always provide a command line paramter -gui. Depending on the flags, both .exe and .com can start the other program if the other mode is requested explicitly. BTW, I learned this behavior von Visual Studio: They ship both a devenv.exe (the regular Visual Studio GUI application) and a devenv.com (to be used by build tools).

                      JonBJ 1 Reply Last reply
                      2
                      • S SimonSchroeder

                        If I remember correctly, there are ways to reattach the console for a GUI application. I have found some old code of mine like this:

                        void openConsole()
                        {
                            AllocConsole();
                            std::freopen( "CON", "w", stdout );
                            std::freopen( "CON", "w", stderr );
                            std::freopen( "CON", "r", stdin );
                        }
                        

                        This function is called if the GUI application is started in non-GUI mode.

                        However, my solution for an app that works both as command line and GUI application on Windows is to compile two separate binaries. The GUI is the .exe file and the command line version is the .com file (command file). On the command line a .com file is preferred to a .exe file if you just type in the file name without the suffix. Also, I tend to make the non-GUI version the default because the GUI .exe is usually started through a shortcut and the shortcut can be set to always provide a command line paramter -gui. Depending on the flags, both .exe and .com can start the other program if the other mode is requested explicitly. BTW, I learned this behavior von Visual Studio: They ship both a devenv.exe (the regular Visual Studio GUI application) and a devenv.com (to be used by build tools).

                        JonBJ Offline
                        JonBJ Offline
                        JonB
                        wrote last edited by JonB
                        #22

                        @SimonSchroeder said in Checking if running as command-line (QCoreApplication) or GUI:

                        If I remember correctly, there are ways to reattach the console for a GUI application. I have found some old code of mine like this:

                        No! You use AllocConsole() which

                        Allocates a new [my bold] console for the calling process.

                        which does not access the Command Prompt/console from which you invoke it ("reattach the console"), nor can it be used in pipe sequences or with redirection etc. It is simply a Windows/GUI executable which happens to open its own console for some purpose.

                        VS ships devenv.exe as a windows executable and a completely separate executable, devenv.com as a console one. Which is precisely what I have been saying/suggesting all along: you need a separate executable, linked as console not windows, for a proper "command line" executable. And I am suggesting that if code you link with has #include <QApplication> if (qApp) ... it will have to be windows and therefore not a proper command line, regardless of whether it creates a QApplication or a QCoreApplication at runtime. Which somebody (perhaps the OP?) who is interested and has Qt for Windows might just like to test....

                        1 Reply Last reply
                        0
                        • JonBJ JonB

                          @Pl45m4
                          Has anyone tried this, especially under Windows, to see what kind of "non-GUI version" you get? My understanding/suspicion is it will be a windows application (even if it opens no windows/widgets) which does not use/cannot access the console from which it is run, does not have open stdin/out/err and so on? Based on how MSVC non-Qt applications work.

                          Pl45m4P Offline
                          Pl45m4P Offline
                          Pl45m4
                          wrote last edited by Pl45m4
                          #23

                          @JonB

                          I also referenced it in my topic (here) already, where I was playing with hybrid app approaches, because I had the idea of making one app binary in total that would work in CLI and GUI mode.
                          But it turned out, that you have to add quite some platform specific code (directing IO from/to the console, etc...) to make it look smooth without any bugs and "blinking console windows" in the background.
                          So I went for a launcher (3-way targets). One GUI binary, one CLI binary and one launcher for convenience where you can select (manually or by arg to make it default -> myAppLauncher.exe -gui) the mode you want to run. Then it starts the right program.


                          If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                          ~E. W. Dijkstra

                          JonBJ 1 Reply Last reply
                          1
                          • Pl45m4P Pl45m4

                            @JonB

                            I also referenced it in my topic (here) already, where I was playing with hybrid app approaches, because I had the idea of making one app binary in total that would work in CLI and GUI mode.
                            But it turned out, that you have to add quite some platform specific code (directing IO from/to the console, etc...) to make it look smooth without any bugs and "blinking console windows" in the background.
                            So I went for a launcher (3-way targets). One GUI binary, one CLI binary and one launcher for convenience where you can select (manually or by arg to make it default -> myAppLauncher.exe -gui) the mode you want to run. Then it starts the right program.

                            JonBJ Offline
                            JonBJ Offline
                            JonB
                            wrote last edited by
                            #24

                            @Pl45m4
                            I entirely agree. And the conclusion you seem to have come to there is indeed that things either do not quite work or they are at best tricky if you try to make a windows-linked executable behave as a "proper" command-line executable at runtime.

                            Also I cannot spot it but I believe we had another topic discussing this at length recently/a while back and coming to the conclusion that you need a "wrapper" command -line executable to launch the underlying GUI versus command line code executables if you want a single program "entry point". It may have been your topic but I have a feeling it was a more recent one.

                            Pl45m4P 1 Reply Last reply
                            1
                            • PerdrixP Offline
                              PerdrixP Offline
                              Perdrix
                              wrote last edited by
                              #25

                              As far as I (the OP) am concerned this issue is closed. Build for GUI, build separate code for CL, have common base class for issuing messages and subclass for either GUI or CL as needed.

                              D.

                              JonBJ 1 Reply Last reply
                              0
                              • JonBJ JonB

                                @Pl45m4
                                I entirely agree. And the conclusion you seem to have come to there is indeed that things either do not quite work or they are at best tricky if you try to make a windows-linked executable behave as a "proper" command-line executable at runtime.

                                Also I cannot spot it but I believe we had another topic discussing this at length recently/a while back and coming to the conclusion that you need a "wrapper" command -line executable to launch the underlying GUI versus command line code executables if you want a single program "entry point". It may have been your topic but I have a feeling it was a more recent one.

                                Pl45m4P Offline
                                Pl45m4P Offline
                                Pl45m4
                                wrote last edited by Pl45m4
                                #26

                                @JonB

                                There's also the difference between the nowadays common "headless" mode for GUI apps and console applications.
                                Every console app can be considered "headless", but not every headless-capable app is console only... some just don't show any toplevel window, but are still built as a WIN32 executable target while running in the background (or as SysTray app process).
                                So yeah, I think one executable for both worlds is pretty hard to build and maintain [maintain pun not intended :)) ]
                                -> Speaking of entry points WinMain() vs. main(), console io redirection, window handling etc.

                                There were quite some discussions, but also can't find them right now :))


                                If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                                ~E. W. Dijkstra

                                1 Reply Last reply
                                0
                                • PerdrixP Perdrix

                                  As far as I (the OP) am concerned this issue is closed. Build for GUI, build separate code for CL, have common base class for issuing messages and subclass for either GUI or CL as needed.

                                  D.

                                  JonBJ Offline
                                  JonBJ Offline
                                  JonB
                                  wrote last edited by JonB
                                  #27

                                  @Perdrix said in Checking if running as command-line (QCoreApplication) or GUI:

                                  As far as I (the OP) am concerned this issue is closed. Build for GUI, build separate code for CL, have common base class for issuing messages and subclass for either GUI or CL as needed.

                                  And I asked you whether you had actually tried building/linking your code, with the qApp module, at least under Windows if that is what you use, to see whether it is truly "command line", e.g. does it do redirection like echo abc | yourexecutable > file? Maybe you don't care, maybe you're not under Windows, whatever: I have said what I can, i leave it to you now.

                                  1 Reply Last reply
                                  0
                                  • PerdrixP Offline
                                    PerdrixP Offline
                                    Perdrix
                                    wrote last edited by
                                    #28

                                    @JonB I'm up to my **** in stuff so don't really feel I want to spend the time doing that investigation.

                                    It would be informative for sure, but I have to prioritise ...

                                    1 Reply Last reply
                                    0

                                    • Login

                                    • Login or register to search.
                                    • First post
                                      Last post
                                    0
                                    • Categories
                                    • Recent
                                    • Tags
                                    • Popular
                                    • Users
                                    • Groups
                                    • Search
                                    • Get Qt
                                    • Unsolved