I'm trying to create a console application with Qt
and been facing really strange behavior when attempting to retrieve the arguments. My class is derived from QCoreApplication
which has a function that should normally put all the args in some list of strings
. But in some cases that call ends in a segmentation fault.
Here's the code:
main.cpp
#include "Diagramm.h"
int main(int argc, char *argv[])
{
Diagramm application(argc, argv);
application.run();
return EXIT_SUCCESS;
}
Diagramm.h
#include <QCoreApplication>
#include <iostream>
#include <QStringList>
#include <QFile>
#include <QDebug>
class Diagramm : public QCoreApplication
{
Q_OBJECT
public:
Diagramm(int argc, char *argv[]);
void run();
private:
void testArguments();
signals:
public slots:
};
Diagramm.cpp
#include "Diagramm.h"
Diagramm::Diagramm(int argc, char *argv[]) : QCoreApplication(argc, argv)
{
//std::cout << "calling Diagramm constructor" << std::endl;
}
void Diagramm::run()
{
testArguments();
}
void Diagramm::testArguments()
{
//get source and target files from arguments
QStringList arguments = this->arguments();
if(arguments.count() < 2)
{
std::cout << "Missing arguments" << std::endl;
return exit(1);
}
}
When compiling and executing the code above, everything works fine, BUT when I uncomment the line in Diagramm
's constructor I've got a segmentation fault on the first line of function testArguments
(the call to arguments()
)
I've been on that for hours, reading Qt's doc, forums... Does anyone know where that can come from? Any idea would be greatly appreciated.
Note : I'm not calling the exec
function on purpose because I don't need any event loop.
Q(Core)Application wants argc
and argv
by reference, so your constructor should read
Diagramm(int& argc, char **argv[])
If you don't to this, it may work in some cases and lead to segfaults or strange behavior in others, as you encountered. Seems to be a common error and isn't easy to spot when reading the documentation.
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