Can I use QCommandLineParser to determine GUI mode or CLI mode? - qt

One of the programs that I work with has two modes that it can run in: GUI (Graphical User Interface) mode or CLI (Command-Line Interface) mode. We determine which mode to use via a command line argument (i.e., if "--cli" is passed, it will use CLI mode).
The type of QApplication that is instantiated depends on which mode is used: QApplication should be used for GUI mode, and QCoreApplication should be used for CLI mode, because the GUI parts of Qt should not be instantiated for CLI mode (since CLI mode does not use or need them).
I can do that via code similar to the following:
std::unique_ptr<QCoreApplication> app =
(cliMode) ? std::make_unique<QCoreApplication>(argc, argv)
: std::make_unique<QApplication>(argc, argv);
// Do some other stuff...
return app->exec();
Since I am already using Qt, it makes sense to use QCommandLineParser to parse my arguments. After parsing the arguments, I want to analyze them to determine whether we should run in GUI mode or CLI mode. However, it has been becoming increasingly difficult to do so.
The first problem I noticed was the following on Linux (this did not happen in older versions of Qt5, but it does happen in the newer versions):
$ ./myQtApplication --help
QCoreApplication::arguments: Please instantiate the QApplication object first
Segmentation fault (core dumped)
Okay: so I can no longer run the --help command without already having a QApplication object instantiated. I temporarily fixed this by manually parsing the arguments to see whether or not --help is an argument. If it is, go ahead and instantiated the QCoreApplication, parse the arguments, and then exit.
But then I started getting a cryptic error on Mac OS X. When I would run the executable on OS X directly, it would run without any issues. But if I tried to double-click on the .app file or type in the terminal $ open myQtApplication.app, I would get this cryptic error:
LSOpenURLsWithRole() failed with error -10810 for the file ./myQtApplication.app
Since it is a rather cryptic error, it took me a long time to figure out that this error was being caused by the QCommandLineParser being used before having a QApplication object instantiated.
To fix this, I am now doing the following:
Manually parse the arguments at the beginning of the main() function to determine whether or not --cli was passed.
Instantiate a QApplication object based on the results of #1.
Run QCommandLineParser to process the rest of the arguments.
This is not a very clean way to do this because I now have two argument parsers: one to determine if --cli was passed, and the rest for the other arguments.
Is there a much better, or "proper", way to do this?
I guess the main question is: can I use QCommandLineParser to determine whether to instantiate a QCoreApplication object or a QApplication object?

Of course you can use the parser - as long as QCoreApplication already present. If the --cli option is absent, you will switch to a QApplication. Recall that you have full control over the lifetime of the application object.
This works under Qt 4.8 and 5.11 on both Windows and OS X:
// https://github.com/KubaO/stackoverflown/tree/master/questions/app-cli-gui-switch-52649458
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QtWidgets>
#endif
struct Options {
bool cli;
};
static Options parseOptionsQt4() {
Options opts = {};
for (auto arg : QCoreApplication::arguments().mid(1)) {
if (arg == "--cli")
opts.cli = true;
else
qFatal("Unknown option %s", arg.toLocal8Bit().constData());
}
return opts;
}
static Options parseOptions() {
if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) return parseOptionsQt4();
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
Options opts = {};
QCommandLineParser parser;
QCommandLineOption cliOption("cli", "Start in command line mode.");
parser.addOption(cliOption);
parser.process(*qApp);
opts.cli = parser.isSet(cliOption);
return opts;
#endif
}
int main(int argc, char *argv[]) {
QScopedPointer<QCoreApplication> app(new QCoreApplication(argc, argv));
auto options = parseOptions();
if (options.cli) {
qDebug() << "cli";
} else {
qDebug() << "gui";
app.reset();
app.reset(new QApplication(argc, argv));
}
if (qobject_cast<QApplication *>(qApp))
QMessageBox::information(nullptr, "Hello", "Hello, World!");
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
return app->exec();
}

Related

OpenMP code in CUDA source file not compiling on Google Colab

I am trying to run a simple Hello World program with OpenMP directives on Google Colab using OpenMP library and CUDA. I have followed this tutorial but I am getting an error even if I am trying to include %%cu in my code. This is my code-
%%cu
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
/* Main Program */
int main(int argc , char **argv)
{
int Threadid, Noofthreads;
printf("\n\t\t---------------------------------------------------------------------------");
printf("\n\t\t Objective : OpenMP program to print \"Hello World\" using OpenMP PARALLEL directives\n ");
printf("\n\t\t..........................................................................\n");
/* Set the number of threads */
/* omp_set_num_threads(4); */
/* OpenMP Parallel Construct : Fork a team of threads */
#pragma omp parallel private(Threadid)
{
/* Obtain the thread id */
Threadid = omp_get_thread_num();
printf("\n\t\t Hello World is being printed by the thread : %d\n", Threadid);
/* Master Thread Has Its Threadid 0 */
if (Threadid == 0) {
Noofthreads = omp_get_num_threads();
printf("\n\t\t Master thread printing total number of threads for this execution are : %d\n", Noofthreads);
}
}/* All thread join Master thread */
return 0;
}
And this is the error I am getting-
/tmp/tmpxft_00003eb7_00000000-10_15fcc2da-f354-487a-8206-ea228a09c770.o: In function `main':
tmpxft_00003eb7_00000000-5_15fcc2da-f354-487a-8206-ea228a09c770.cudafe1.cpp:(.text+0x54): undefined reference to `omp_get_thread_num'
tmpxft_00003eb7_00000000-5_15fcc2da-f354-487a-8206-ea228a09c770.cudafe1.cpp:(.text+0x78): undefined reference to `omp_get_num_threads'
collect2: error: ld returned 1 exit status
Without OpenMP directives, a simple Hello World program is running perfectly as can be seen below-
%%cu
#include <iostream>
int main()
{
std::cout << "Welcome To GeeksforGeeks\n";
return 0;
}
Output-
Welcome To GeeksforGeeks
There are two problems here:
nvcc doesn't enable or natively support OpenMP compilation. This has to be enabled by additional command line arguments passed through to the host compiler (gcc by default)
The standard Google Colab/Jupyter notebook plugin for nvcc doesn't allow passing of extra compilation arguments, meaning that even if you solve the first issue, it doesn't help in Colab or Jupyter.
You can solve the first problem as described here, and you can solve the second as described here and here.
Combining these in Colab got me this:
and then this:

Why do QProcess (Qt 5.15.1) and GDB lead to missing symbols?

I am currently having some trouble debugging a program that starts processes via QProcess.
Simply executing the binary without dbg works just fine but when I try to debug the executable with gdb I am getting a SIGTRAP when the process has started.
After that the stack always shows '??' instead of function names.
When continuing I get a SIGILL.
I found out that the trap is not caused when no breakpoint is set.
In my project I also get following output:
Probes-based dynamic linker interface failed.
I am not sure whether this is related to loaded plugins or libraries.
The problem can be reproduced (except from the " Probes-based dynamic linker interface failed." output) with the following code:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QProcess proc;
QString exe = "echo";
QStringList arguments;
arguments << "Test";
proc.start(exe, arguments);
if (!proc.waitForFinished()) {
qDebug() << "failed to start" << proc.exitCode() << proc.errorString();
}
qDebug() << "process finished";
qDebug() << proc.readAllStandardOutput();
return a.exec();
}
My OS is arch linux (up to date)
Qt5: qt5-base 5.15.1-1
GDB: gdb 9.2-1
clang++: clang 10.0.1-1
Does anybody have an idea what is causing the SIGTRAP when debugging with dbg?

Getting the Qt Creator test scanner to find all test classes in one project

Our team uses Qt Creator. We have quite large projects, and for each project we have a test project with a test class for every production class. The main of the test project calls QTest::qExec for every test class. We run our tests by simply running the test project.
That works fine, but the output is limited to the console, looking like this:
********* Start testing of TestClass1 *********
Config: Using QtTest library 5.10.1, Qt 5.10.1 (x86_64-little_endian-lp64 shared (dynamic) debug build; by GCC 7.3.0)
PASS : TestClass1::initTestCase()
PASS : TestClass1::test1()
PASS : TestClass1::test2()
PASS : TestClass1::cleanupTestCase()
Totals: 2 passed, 0 failed, 0 skipped, 0 blacklisted, 3ms
********* Finished testing of TestClass1*********
********* Start testing of TestClass2 *********
Config: Using QtTest library 5.10.1, Qt 5.10.1 (x86_64-little_endian-lp64 shared (dynamic) debug build; by GCC 7.3.0)
PASS : TestClass2::initTestCase()
PASS : TestClass2::test1()
PASS : TestClass2::test2()
PASS : TestClass2::cleanupTestCase()
Totals: 2 passed, 0 failed, 0 skipped, 0 blacklisted, 3ms
********* Finished testing of TestClass2*********
I just discovered the integrated test gui and would really like to use it. However, I can't get the scanner (Tools->Tests->Rescan tests) to find all tests in a project. If I write this in the main it works fine for TestClass1:
int main(int argc, char** argv) {
TestClass1 test;
return QTest::qExec(&test, argc, argv);
}
However, if I try to add TestClass2 as below the scanner only recognizes TestClass2:
int main(int argc, char** argv) {
TestClass1 test1;
int ret = QTest::qExec(&test1, argc, argv);
TestClass2 test2;
int ret &= QTest::qExec(&test2, argc, argv);
return ret;
}
It seem as if the scanner only finds the last class executed with QTest::qExec.
Any idea how I could get it to find all tests, without touching the existing test classes?

qDebug not showing __FILE__,__LINE__

According to qlogging.h
#define qDebug QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug
but when I use like this, file,line,function name not show.
qDebug()<< "abc"; // only show abc;
qDebug()<< ""; // show nothing;
I search for a while, it seems no one had my problem like above.
I use ubuntu14.04,g++ version 4.8.2, qt5.3 build from git.
You can reformat from default output format.
This function was introduced in Qt 5.0.
The line number does not output because the default message pattern is "%{if-category}%{category}: %{endif}%{message}". This format means that the default outputting format is not including metadata like a line number or file name.
% cat logtest.pro
TEMPLATE = app
TARGET = logtest
mac:CONFIG-=app_bundle
SOURCES += main.cpp
% cat main.cpp
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
qSetMessagePattern("%{file}(%{line}): %{message}");
QCoreApplication a(argc, argv);
qDebug() << "my output";
return 0;
}
% qmake && make
% ./logtest
main.cpp(8): my output
You can also use QT_MESSAGE_PATTERN environment variable for setting the message pattern without calling qSetMessagePattern().
See reference for other placeholder. http://qt-project.org/doc/qt-5/qtglobal.html#qSetMessagePattern
If you dig in Qt history you can find out that the __FILE__ and __FUNCTION__ are logged only in debug builds since 1 Oct 2014. The git commit hash is d78fb442d750b33afe2e41f31588ec94cf4023ad. The commit message states:
Logging: Disable tracking of debug source info for release builds
Tracking the file, line, function means the information has to be
stored in the binaries, enlarging the size. It also might be a
surprise to some commercial customers that their internal file &
function names are 'leaked'. Therefore we enable it for debug builds
only.
Here's a simple example of how you might use the captured QMessageLogContext data in a custom message handler installed using qInstallMessageHandler. I didn't output the category or version members because they didn't seem useful. If desired you could also log to a file this way.
#include <QDebug>
#include <QString>
#include <QDateTime>
#include <iostream>
void verboseMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static const char* typeStr[] = {"[ Debug]", "[ Warning]", "[Critical]", "[ Fatal]" };
if(type <= QtFatalMsg)
{
QByteArray localMsg = msg.toLocal8Bit();
QString contextString(QStringLiteral("(%1, %2, %3)")
.arg(context.file)
.arg(context.function)
.arg(context.line));
QString timeStr(QDateTime::currentDateTime().toString("dd-MM-yy HH:mm:ss:zzz"));
std::cerr << timeStr.toLocal8Bit().constData() << " - "
<< typeStr[type] << " "
<< contextString.toLocal8Bit().constData() << " "
<< localMsg.constData() << std::endl;
if(type == QtFatalMsg)
{
abort();
}
}
}
int main()
{
//Use default handler
qDebug() << "default handler";
qWarning() << "default handler";
qCritical() << "default handler";
//Install verbose handler
qInstallMessageHandler(verboseMessageHandler);
qDebug() << "verbose handler";
qWarning() << "verbose handler";
qCritical() << "verbose handler";
//Restore default handler
qInstallMessageHandler(0);
qDebug() << "default handler";
qWarning() << "default handler";
qCritical() << "default handler";
return 0;
}
You can use standard C++'s __LINE__ and __FILE__. Also, take a look at What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__ SO question. If you use GCC, you can write __PRETTY_FUNCTION__ to get information about function from where the code executes. Just prepare debug-define you like.
For example, here is small compilable application:
#include <QApplication>
#include <QDebug>
#include <iostream>
// Qt-way
#define MyDBG (qDebug()<<__FILE__<<__LINE__<<__PRETTY_FUNCTION__)
// GCC
#define MyStdDBG (std::cout<< __FILE__<<":"<<__LINE__<<" in "<<__PRETTY_FUNCTION__<<std::endl)
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Qt-way
MyDBG;
MyDBG << "Something happened!";
// GCC
MyStdDBG;
return a.exec();
}
It gives next output:
../path/main.cpp 14 int main(int, char**)
../path/main.cpp 15 int main(int, char**) Something happened!
../path/main.cpp:18 in int main(int, char**)
UPD: Added pure C++-way to output.
I think you need to define:
#define qDebug() QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug()
and use it as
qDebug() << "abc";
or
#define qDebug QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug()
and use it as:
qDebug << "abc";
According to documentation qDebug() is already a macro to QMessageLogger(). Default Message handler prints only the message to stderr. I think you might want to use qInstallMessageHandler() to install your own message handler, that uses the context
Edit:
There is a relevant section in a manual, that describes this issue. In Qt4 context variable was not passed to installed message handler, so this solution is Qt5+ only. Default message handler does not make use of passed in context, but you can easily install your own, it's just a function pointer. There is even an example in the manual.
This depends on your Qt version number, whether you are using a debug build or a release build of Qt, and whether you have customized Qt message handling in your application.
According to Qt 5.4 documentation written in source code "qlogging.cpp":
QMessageLogger is used to generate messages for the Qt logging framework. Usually one uses
it through qDebug(), qWarning(), qCritical, or qFatal() functions,
which are actually macros: For example qDebug() expands to
QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug()
for debug builds, and QMessageLogger(0, 0, 0).debug() for release builds.
So if you do not see file, line and function name information in your output, very likely you are using a release version of Qt.
If you still want to see the file, line and function name information in your output with a release version of Qt, there are several ways of achieving it, as very well explained in some of the previous answers.
If you wonder how to get the debug context in a non-debug build: Define QT_MESSAGELOGCONTEXT while compiling your code, and the information won't be stripped:
http://doc.qt.io/qt-5/qmessagelogcontext.html

QProcess::readAllStandardOutput gives flaky outputs

I am trying to create a GUI in Qt4 for my tcl based tool. In order to populate widgets I need to execute some tcl commands. I read about QProcess and I am invoking tcl scripts using QProcess and then grabbing their output from stdout.
Suppose I execute 3 commands in tcl then when I query stdout I believe I should see 3 outputs corresponding to each of the three commands, however this is not happening consistently. Behavior is flaky.
As you can see in the main.cpp I am executing multiple commands using runTclCommand() function and in the end executing getData() function to read stdout.
main.cpp:
#include <QApplication>
#include <QProcess>
#include <QDebug>
#include "Tclsh.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QByteArray out;
Tclsh *tcl = new Tclsh;
tcl->startTclsh();
tcl->runTclCommand("set ::tcl_interactive 1\n");
tcl->runTclCommand("set a 23\n");
tcl->runTclCommand("puts $a\n");
tcl->runTclCommand("set a 40\n");
tcl->runTclCommand("puts $a\n");
// out = idl->getData();
out = tcl->getData();
}
Tclsh.cpp:
#include <QProcessEnvironment>
#include <QProcess>
#include <QDebug>
#include "Tclsh.h"
void Tclsh::startTclsh() {
QString program = "/usr/bin/tclsh8.4";
this->setProcessChannelMode(QProcess::MergedChannels);
this->start(program);
if ( !this->waitForStarted()) {
qDebug()<<"ERROR Starting tclsh";
}
return;
}
void Tclsh::runTclCommand(const char *cmd) {
qDebug()<<"CMD:"<<cmd;
this->write(cmd);
if (!this->waitForBytesWritten()) {
qDebug()<<"Error in writing data";
}
}
QByteArray Tclsh::getData() {
if (!this->waitForReadyRead()) {
qDebug()<<"Error in reading stdout: Ready read signal is not emitted";
}
QByteArray data = this->readAllStandardOutput();
qDebug()<<"DATA:"<<data;
return data;
}
However, sometime I get the following output:
CMD: set ::tcl_interactive 1
CMD: set a 23
CMD: puts $a
CMD: set a 40
CMD: puts $a
DATA: "1
% 23
% 23
% "
And sometimes this:
CMD: set ::tcl_interactive 1
CMD: set a 23
CMD: puts $a
CMD: set a 40
CMD: puts $a
DATA: "1
"
I do not understand why this is happening. I would really appreciate if someone can point me to the error in my approach here.
Thanks,
Newbie
Edit: After some more research, here are my thoughts
According to Qt manual, readyRead signal will be emitted whenever new data is available (as specified by #Frank Osterfeld also, thanks!). It will not wait for complete output data to be available (which is justified since it does not know when will that happen). Hence my approach is not good. What I can do is something like this:
start the process -> wait for process to finish -> read stdout
This will ensure that flaky behavior does not arise as process is already finished when I am reading hence no new data can come.
However, in this proposed approach I am not clear about one thing: Does stdout is specific to a process? I mean can it happen that process which was supposed to read stdout output from process1, can get other stdout data from some other process which happen to write stdout at the same time as process1?
Thanks,
Newbie
I am closing this question. Reading from a channel more than once does not seem to a be a good idea. Instead what I do now is write what I want to write in one go --> close the channel for writing --> then read it back. In that way I get consistent output.

Resources