How can I use C++14 features when building qmake projects?

岁酱吖の 提交于 2019-11-27 09:02:25

Qt Creator is just an IDE.

You can think of IDEs as "smarter text editors" that aid the developer with debugging, building, code completion, file management and so on.

IDEs are irrelevant during compilation.

What matters is your compiler. And it is independent from your IDE.

g++ 4.8.x does not support many C++14 features: check out this page to learn what C++14 features are supported.

This is now supported properly from Qt 5.4. You just type this into your qmake project file:

CONFIG += c++14

The necessary code change went in the middle of 2014 by Thiago:

Add support for CONFIG += c++14

I have just created the necessary documentation change:

Mention the c++14 CONFIG option in the qmake variable reference

Please note that variable templates are only supported from gcc 5.0, but then your code works just fine. This can be used for testing C++14 with older gcc:

main.cpp

#include <iostream>

int main()
{
    // Binary literals: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3472.pdf
    // Single-quotation-mark as a digit separator: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf
    std::cout << 0b0001'0000'0001;
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
CONFIG -= qt
CONFIG += c++14
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

257
pierre

For some weird reason this is what Qt does: If the compiler is gcc or mingw, CONFIG+=C++14 is transformed to a compiler flag -std=c++14 (that what you expect)

If it's another compiler (like clang), CONFIG=C++14 is stupidly transformed to -std=c++11 (sic!), so you will get errors about unsupported features, even if your clang version correctly supports C++14.

To fix it, specify the flag explicitly:

QMAKE_CXXFLAGS += -std=c++14

This way, you're sure that your compiler (g++, mingw or clang) will receive the correct flags.

To use C++14 with qmake with versions before Qt 5.4 (it doesn't make any difference wether you use it with Qt Creator or with some other IDE or from command line) and gcc, add this to your .pro file:

QMAKE_CXXFLAGS += -std=c++1y

qmake got support for CONFIG += c++14 with Qt 5.4, so you can use that for projects where you are comfortable with requiring at least that version of Qt. Be sure to either use the explicit compiler flags, or use the CONFIG option, but not both at the same time, to avoid conflicting switches.


Unfortunately gcc 4.8.2 supports very few C++14 features (see here), but you can test that with this code snippet:

#include <iostream>

auto f() { return 42; }

int main()
{
    std::cout << f() << std::endl;
}

That will compile fine with QMAKE_CXXFLAGS += -std=c++1y, but give warning with CONFIG += c++11 or QMAKE_CXXFLAGS += -std=c++1x.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!