Evgenii Legotckoi
Evgenii LegotckoiJuly 28, 2016, 11:40 a.m.

Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers

Initial acquaintance with Boost on Windows start to build precompiled libraries and connecting them to the project on Qt. This code will use one of the Hello World-s from the Boost documentation, namely the installation locale using boost.

Building Boost for MinGW

First, download the latest version of Boost (as of this writing is version 1.61) and unpack the archive into a folder. In my case, the archive is unpacked in the following path:

D:\EVILEG\boost_1_61_0

Then open the console and go to the folder. In this folder there is a batch file to build bootstrap.bat bjam tool, which is designed to control compilation target libraries under the compiler.

To build this tool for MinGW run the following command:

bootstrap.bat gcc

Once the tool is assembled perform the assembly of all the necessary libraries with the following command:

b2 toolset=gcc link=shared --prefix=boost_mingw_530 install  // , where
    // toolset  - this tool, which will be collected in the library, 
    //            ie the type of compiler, which you will collect the library
    // link     - this type of library, in this case the shared - dynamic
    // --prefix - folder which will be copied the header files and libraries compiled
    //            in my case D:\EVILEG\boost_1_61_0\boost_mingw_530

Then you can go about their business, because this process is not fast.


Note

Note that the compiler option, which will be collected by the library will be determined by what environment variables are registered in your operating system. That is, on what path is registered to the g ++ compiler in the PATH variable.

I have previous versions of Qt were prescribed way:

D:\Qt\5.6\mingw49_32\bin;
D:\Qt\Tools\mingw490_32\bin;

And, accordingly, the output I got a library for MinGW 4.9.2 compiler. Yes, I have not yet had time to remove the previous version of Qt 5.6 with MinGW 4.9.2. Needless to say, I have a project Qt5.7 with compiler MinGW 5.3.0 refused to be collected?

So after prescribing the right ways managed to collect the necessary libraries:

D:\Qt\5.7\mingw53_32\bin;
D:\Qt\Tools\mingw530_32\bin;

Building Boost for MSVC

The process is completely analogous to that for MinGW, but with a small difference in the commands.

bootstrap.bat vc12    // Пока использую MSVC 2013 Community
b2 toolset=msvc-12.0 link=shared --prefix=boost_msvc install

During assembly, there may be some errors which are also due in varying ways OS. For example like this:

"cl" не является внутренней или внешней командой ... и т.д.

It is treated by prescribing the ways to the compiler MSVC, for example:

D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin;

Also, there can be problems that will not be the path to the header files of the standard library. What is expressed in bootstrap.log information file:

###
### Using 'vc12' toolset.
###

D:\EVILEG\boost_1_61_0\tools\build\src\engine>if exist bootstrap rd /S /Q bootstrap 

D:\EVILEG\boost_1_61_0\tools\build\src\engine>md bootstrap 

D:\EVILEG\boost_1_61_0\tools\build\src\engine>cl /nologo /RTC1 /Zi /MTd /Fobootstrap/ /Fdbootstrap/ -DNT -DYYDEBUG -wd4996 kernel32.lib advapi32.lib user32.lib /Febootstrap\jam0  command.c compile.c constants.c debug.c execcmd.c execnt.c filent.c frames.c function.c glob.c hash.c hdrmacro.c headers.c jam.c jambase.c jamgram.c lists.c make.c make1.c object.c option.c output.c parse.c pathnt.c pathsys.c regexp.c rules.c scan.c search.c subst.c timestamp.c variable.c modules.c strings.c filesys.c builtins.c md5.c class.c cwd.c w32_getreg.c native.c modules/set.c modules/path.c modules/regex.c modules/property-set.c modules/sequence.c modules/order.c 
command.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
compile.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
constants.c
debug.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
execcmd.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
execnt.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
filent.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
frames.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
function.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
glob.c
d:\evileg\boost_1_61_0\tools\build\src\engine\jam.h(71) : fatal error C1034: ctype.h: no include path set
hash.c

Also take some voodoo with paths, or even reinstall the MSVC, or you can go for the most simple way, that will save the nerve cells, and simply download the Boost precompiled libraries from the site.

Connecting Boost to Qt project

For the initial connection Boost prepare a simple console application that will display the time, date and even some information with installation locale via Boost.locale library.

The project will consist of only two files:

  1. QtBoostHello.pro
  2. main.cpp

QtBoostHello.pro

Depending on the compiler you are connecting the necessary header files and libraries:

  • INCLUDEPATH - connect the header files
  • LIBS - connection libraries
QT += core
QT -= gui

CONFIG += c++11

TARGET = QtBoostHello
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

win32-g++ {
    INCLUDEPATH += D:/EVILEG/boost_1_61_0/boost_mingw_530/include/boost-1_61
    LIBS += -LD:/EVILEG/boost_1_61_0/boost_mingw_530/lib -llibboost_locale-mgw53-mt-1_61
} else:win32-msvc* {
    INCLUDEPATH += D:/EVILEG/boost_1_61_0/boost_msvc_2012/include/boost-1_61
    LIBS += -LD:/EVILEG/boost_1_61_0/boost_msvc_2012/lib -lboost_locale-vc120-mt-1_61
}

SOURCES += main.cpp

main.cpp

In the main function there is one of the classes from the Boost library - a generator. Deep will not dig, we also need to start the project. We note only that it is used to set the locale, as shown in the code.

Also, for this class uses a dynamic library. But it is not necessary for all functional library, part of the Boost - This template functions, which are fully defined in the header files.

#include <QCoreApplication>
#include <boost/locale.hpp>

using namespace boost::locale;
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    generator gen;
    locale loc=gen("en_US.UTF-8");
    locale::global(loc);
    // Make it system global

    cout.imbue(loc);
    // Set as default locale for output

    cout <<format("Hello {1,date} at {1,time} we had run our first localization example") % time(0)
          <<endl;

    cout<<"This is how we show numbers in this locale "<<as::number << 103.34 <<endl;
    cout<<"This is how we show currency in this locale "<<as::currency << 103.34 <<endl;
    cout<<"This is typical date in the locale "<<as::date << std::time(0) <<endl;
    cout<<"This is typical time in the locale "<<as::time << std::time(0) <<endl;


    return a.exec();
}

At the output we get the result as in the image below. If you play with a specific locale, ie, instead of "en_US.UTF-8" write "ru_RU.UTF-8", you will notice that the date and time format will change, however, as currency.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

D
  • Nov. 2, 2023, 3:41 a.m.

С CMake всё на много проще:
find_package(Boost)

J
  • Dec. 15, 2023, 6:43 a.m.
  • (edited)

Евгений, здравствуйте! Сделал аналогично вашим рекомендациям, но не может связать файлы. В чём может быть причина?

Evgenii Legotckoi
  • Dec. 15, 2023, 9:46 a.m.

Добрый день! У вас в про файле в строке LIBS += явно не хватает пробела, посмотрите внимательно на свой код и на пример.

J
  • Dec. 15, 2023, 10:08 a.m.
  • (edited)

Евгений, благодарю: с тем вопросом разобрался. Но никак не могу разобрать уже другую

Нашёл пару советов в форуме Qt и stackoverflow, но не понимаю как их реализовать тут. К примеру:

В Asio должна быть ссылка на дополнительные библиотеки. Добавьте в свой LIBS +=
1.) Boost_system: -LC:/path/to/boost/libs и -llibboost_system-mgw48-mt-1_52
2.) В Windows, WS2_32.lib: -LC:/path/to/winsock2/lib и -lWS2_32

https://forum.qt.io/topic/53532/solved-qt-and-boost-cannot-find-llibboost_filesystem/4

Не очень понимаю как реализовать вторую рекомендацию

Evgenii Legotckoi
  • Dec. 15, 2023, 11:07 a.m.

По существу выглядит так, что нужно добавить ещё одну строку;

LIBS += -LC:/path/to/winsock2/lib -lWS2_32

Вот только у вас ещё должна быть эта библиотека winsock2 скачана и находится по этому пути. Но я с таким не сталивался в принципе.

G
  • Dec. 18, 2023, 9:01 p.m.

Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 2:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 2:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 2:35 p.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 3:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks