-1

For my application I had to derive QtCoreApplication and use QCommandLineParser. I declared QCommandLineOptions instances in a separate namespace and wanted to declare the parser in this namepsace as well. However I get an error that I don't quite understand.

namespace
{
    QCommandLineParser parser;
    
    const QCommandLineOption optA("optA", "defaultOptA");
    parser.addOption(optA); <-- error: unknown type name 'parser'
}

MyApp::MyApp(int argc, char *argv[])
    :QCoreApplication(argc, argv)
{
    setApplicationName("My App");
}

I have also tried declaring a QList<QCommandLineOption> so that I can add the options to it and add it the parser in on go using QCommandLineParser::addOptions, but that does not work either.

namespace
{
    QList<QCommandLineOption> options;
    
    const QCommandLineOption optA("optA", "defaultOptA");
    options << optA; <-- error: unknown type name 'options'
}

MyApp::MyApp(int argc, char *argv[])
    :QCoreApplication(argc, argv)
{
    setApplicationName("MyApp);

}

What am I doing wrong in both cases ?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
glamis
  • 85
  • 9
  • The code is not in a function i.e. you have to place `parser.addOption(optA)` or whatever in some function, like `main`. – Rikus Honey Jul 12 '20 at 21:20
  • I would also suggest you make `parser` and `optA` private variables of your `MyApp` class instead of an anonymous namespace. – Rikus Honey Jul 12 '20 at 21:24
  • Why am I not able to use QCommandLineParser outside a function. There is no mention of such behaviour in Qt5 documentation. I only need the object in the current source file so declaring it in an anonymous namespace seems logical right? – glamis Jul 12 '20 at 21:30
  • In `c++` you can't put arbitrary code outside a function. – drescherjm Jul 12 '20 at 21:59

1 Answers1

2

You can't have expressions like parser.addOption(optA) or options << optA in a namespace declaration. This is just C++ thing and has nothing to do with Qt. I would suggest you rather put the parser and optA variables in your MyApp class and initialize them in the MyApp constructor

class MyApp : public QCoreApplication
{
    ...

private:
    QCommandLineParser parser;
    const QCommandLineOption optA;
};

MyApp::MyApp(int argc, char *argv[])
    : QCoreApplication(argc, argv), optA("optA", "defaultOptA")
{
    parser.addOption(optA);
    
    ...
}
Rikus Honey
  • 534
  • 1
  • 3
  • 17