我想在Ubuntu 14.04上的QT创建器中使用C ++ Boost库,在尝试了很多方法后,我仍然会遇到错误。
我使用以下方法安装了Boost库:
sudo apt-get install libboost-all-dev
Boost库安装在以下目录中:
/usr/include/boost
这是我的main.cpp
#include <QCoreApplication>
#include<iostream>
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
boost::asio::steady_timer timer_;
timer_.expires_from_now(1000);
return a.exec();
}
我的.pro文件:
QT += core
QT -= gui
CONFIG += c++11
TARGET = test_boost_lib_in_QT
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
INCLUDEPATH += /usr/include/boost
LIBS += -L/usr/include/boost -lboost_system
LIBS += -L/usr/include/boost -lboost_chrono
LIBS += -L/usr/include/boost -lboost_thread
LIBS += -L/usr/include/boost -lboost_timer
编译错误是:(我使用“ctrl + B”直接从QT编译)
/home/ndn-experiment/Desktop/test_boost_lib_in_QT/main.cpp:13: error: no matching function for call to 'boost::asio::basic_waitable_timer<std::chrono::_V2::steady_clock>::basic_waitable_timer()'
boost::asio::steady_timer timer_;
^
/home/ndn-experiment/Desktop/test_boost_lib_in_QT/main.cpp:14: error: no matching function for call to 'boost::asio::basic_waitable_timer<std::chrono::_V2::steady_clock>::expires_from_now(int)'
timer_.expires_from_now(1000);
^
我该怎么办?
答案 0 :(得分:2)
第一个是因为你需要将io_service
传递给构造函数:
boost::asio::io_service io;
boost::asio::steady_timer timer(io);
第二个是因为expires_from_now
没有int
,它需要一个duration
参数:
timer.expires_from_now(boost::posix_time::seconds(5));
检查documentation是一个很好的总体思路,它有一些用法示例。
答案 1 :(得分:0)
经过互联网上的这么多帖子和我遇到的很多错误后,我终于让我的程序运行了。 在此,我想回答我自己的问题,强调两点:
另一种创建类的对象的方法,其构造函数需要多于1个参数
使用boost::asio::steady_timer
我的main.cpp
#include <QCoreApplication>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <chrono>
#include <boost/chrono.hpp>
using namespace std;
typedef boost::asio::steady_timer timer_type;
class timer_expire{
public:
timer_expire(boost::asio::io_service& io):timer_(io){}
void timer_expires(int n_milliseconds) {
timer_.expires_from_now(boost::chrono::milliseconds(n_milliseconds));
//need timer_.async_wait() here
}
private:
timer_type timer_;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
boost::asio::io_service io;
timer_expire timer_expire_(io);
timer_expire_.timer_expires(10000);
return a.exec();
}
我的.pro文件(请注意QMAKE_CXXFLAGS
)
QT += core
QT -= gui
CONFIG += c++11
TARGET = test_boost_lib_in_QT
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
CONFIG += c++11
QMAKE_CXXFLAGS += -std=c++11
INCLUDEPATH += /usr/include/boost
QMAKE_CXXFLAGS += -DBOOST_ASIO_DISABLE_STD_CHRONO
LIBS += -L/usr/include/boost -lboost_system -lboost_chrono -lboost_thread -lboost_timer
我的g++
版本是4.8.4
请注意,通过将boost::asio::steady_timer
设置为QMAKE_CXXFLAGS
,-DBOOST_ASIO_HAS_STD_CHRONO
还有另一种方法,请参阅此post。
另请查看Chrono。