- Установка Boost под Qt
- Содержание
- Подготовка
- Работаем с Qt
- Сборка для Qt под MinGW
- Сборка для Qt под Visual Studio
- Boost qt creator linux
- How can I include Boost in my Qt Project File?
- 1 Answer 1
- Qt Documentation
- Contents
- Supported Configurations
- Requirements for Development Host
- Debian/Ubuntu (apt-get)
- Fedora/RHEL/CentOS (yum)
- openSUSE (zypper)
- Building Qt 5 from Source
- Deployment and Other Issues
- Where to Go from Here
- Qt/C++ — Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC
- Сборка Boost для MinGW
- Примечание
- Сборка Boost для MSVC
- Подключение Boost к Qt проекту
- QtBoostHello.pro
- main.cpp
Установка Boost под Qt
07.05.2017 1 Comment 16 635 просмотров
Сказ о том, как установить библиотеку Boost для Qt под MinGW и Qt под Visual Studio.
У меня со времени C++ Builder 6 стойкая нелюбовь к непереносимым библиотекам в языках программирования. Когда нужно при переносе проекта в среде разработке что-то дополнительно настраивать и устанавливать. По этой же причине не люблю Boost. Но пришлось недавно им заняться.
Содержание
Подготовка
На сайте http://www.boost.org/ скачиваем последнюю версию библиотеки Boost.
Распакуем архив куда-нибудь и переименуем папку в boost . Я распаковал в корень диска C:\boost .
Работаем с Qt
Собираем библиотеку Boost тем компилятором, которым компилируем наши проекты, где будем использовать Boost.
Под каждый компилятор вам нужно собирать библиотеку отдельно!
Для Qt под MinGW нам потребуется программа gcc.exe .
У меня этот файл находится в папке
На время добавим этот путь в системную перeменную Path.
Сборка для Qt под MinGW
Вызываем командную строку. Например, жмем Win + R . Там вводим cmd и жмем Enter .
Вводим команду. И ждем, когда всё выполнится (всё пройдет быстро)
Вы библиотеку Boost возможно будете собирать под разные версии компиляторов на одном компе. Поэтому в следующей команде укажите название папки, которая создаться в папке C:\boost , куда будут закинуты собранные файлы. Для Qt 5.8 папку назвал boost_mingw_53_32
Вводим команду (не забудьте поменять название папки!). И ждем, когда всё выполнится (а вот это будет не быстро).
И через долгое время (у меня ушло больше 20 минут) библиотека соберется.
Итак, у нас у меня в папке C:\boost\boost_mingw_53_32 собранная библиотека, которую я теперь могу использовать.
Не забудьте удалить путь к gcc.exe из переменной Path . Если вы не удалите, то ничего страшного не случится, но в будущем, когда под другой компилятор или другой версии текущего компилятора будете собирать boost, возникнут проблемы.
И вам нужно удалить только один путь из переменной Path. Не вздумайте удалить всю переменную Path. Это приведет к очень плохим последствиям!
Сборка для Qt под Visual Studio
И если под сборка под MinGW прошла без проволочек, то со сборкой под Visual Studio я намучился.
У меня стоит сразу две версии Qt: под MinGW и под Visual Studio (QWebEngine работает только под Visual Studio).
Тут вместо gcc.exe будет нужен файл cl.exe . У меня стоит Visual Studio 2015, и данный файл находится в папке
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin
Добавляем этот путь временно в системную переменную Path .
Также нам потребуется знание версии Visual Studio. Она не совпадает с названием установленной Visual Studio! У стоит Visual Studio 2015 , а версия vc14 .
Надеюсь, что вы не вышли из командной строки. Если вышли, то войдите заново и перейдите в папку с boost.
Источник
Boost qt creator linux
Hello guys.
I want to install latest version of boost library on Ubuntu in order to use in Qt Creator IDE.
I type the following in terminal:
But this only gives me version 1.65.1 of boost which is for couple of years ago!
Is there any way to install latest binary of boost 1.69.0 without needing to compile it?
Any helps greatly appreciated!
What Linux distribution are you using ?
On a side note, that’s a question you should bring to the boost community.
@SGaist Really thanks man!
My distribution is Ubuntu.
Sorry if topic is not related to Qt’s world!
And which version?
By the way, what do you require from boost that demands the latest version ?
@Nima-Ghorab Not even Debian Sid has the latest boost version, so if you don’t find a third party package, no way to get the latest version. Sorry
@SGaist Just curious to know how can I do that.
@aha_1980 Thanks man I think there is no way to install binary directly and I should compile latest boost version on Ubuntu.
Dear @mrjj I did that but when I want to install it via apt-get it tells me that unable to locate package libboost!
I checked out Software and Updates the repository is successfully added but it doesn’t work!
@Nima-Ghorab
hi
so first you did
$ sudo add-apt-repository ppa:mhier/libboost-latest
$ sudo apt update
and then
sudo apt install libboost
and then it said it didnt know libboost ?
@mrjj Yes exactly I did but it didn’t work!
Is this the same for you?
@Nima-Ghorab
Hi
ahh names are a bit differnt than last time
try
sudo apt install libboost1.68
@mrjj Thank you so much and at the end I have two questions:
1_How did you get that we should use sudo apt install libboost1.68 instead of sudo apt install libboost?
2_Why major repositories don’t update their databases to the latest version of libraries so that users can choose the proper version they want?
Thank you so much!
- Using apt-cache to list the various boost package
- Debian (which Ubuntu is based on) is known to ship packages that are considered stable because they have gone through thorough testing. They have a procedure to follow which means the package has to go first through unstable, then testing and finally stable.
«Latest and greatest» doesn’t fit in the latest category.
All of this work requires time and people.
Most Linux distributions are the result of the work of volunteers who help creating packages and maintaining them. If you need that much a package for a given distribution, you are welcome to help the effort of getting it on it.
@SGaist and @mrjj thank you so much for your great helps.
Источник
How can I include Boost in my Qt Project File?
I have tried to include Boost in Qt Creator since yesterday. But it doesn’t work.
But how do I that with the «.a» files?
Sorry for my bad english.
1 Answer 1
To link external libraries in Qt project you should provide required linker options. Those options can be added to LIBS variable in the .pro file.
Most Windows compilers and linkers have so-called “auto-linking support,” which eliminates the second challenge. Special code in Boost header files detects your compiler options and uses that information to encode the name of the correct library into your object files; the linker selects the library with that name from the directories you’ve told it to search.
The GCC toolchains (Cygwin and MinGW) are notable exceptions; GCC users should refer to the linking instructions for Unix variant OSes for the appropriate command-line options to use.
For MinGW the library search path is added by -Lpath option and the library name that should be linked by -llibrary, where library is the library name dropping the filename’s leading lib and trailing suffix ( .a in this case):
Update according to new log of error messages
You use two different MinGW compilers:
- MinGW 4.9.2 shipped with Qt
- external MinGW 5.1.0 to build Boost
There is too large gap between those compilers and your Boost binaries are not compatible with Qt compiler. I was able to reproduce your error messages using MinGW 5.1.0 for Boost and MinGW 4.8 in my Qt installation.
Build Boost using compiler provided by Qt. Set proper toolchain path for building Boost:
It should work with proper library versions, for example -lboost_regex-mgw492-mt-1_59 .
Note that there are also two types of Boost binaries: release and debug (tagged by -d in file name). According to doc:
Although it’s true that sometimes these choices don’t affect binary compatibility with other compiled code, you can’t count on that with Boost libraries.
So, you may want different project options for debug and release builds. In Qt .pro it can be done by testing CONFIG variable:
Источник
Qt Documentation
Contents
Qt’s support for different Linux platforms is extensive and mature.
To download and install Qt for Linux, follow the instructions on the Getting Started with Qt page.
Supported Configurations
The following configurations are supported.
Distribution | Architecture | Compiler | Notes |
---|---|---|---|
openSUSE 15.1 | x86_64 | GCC 5 or later, GCC 7, ICC 19.1 | |
SUSE Linux Enterprise Server | x86_64 | GCC 5 or later, GCC 10 | |
Red Hat Enterprise Linux 7.6 | x86_64 | GCC 5.3.1 via devtoolset-4 | |
Ubuntu 18.04 | x86_64 | GCC 5 or later, GCC 9 | |
Generic Linux | x86 and x86_64 | GCC (5 or later), ICC 18.x |
Requirements for Development Host
The Qt installers for Linux assume that a C++ compiler, debugger, make, and other development tools are provided by the host operating system. In addition, building graphical Qt applications requires OpenGL libraries and headers installed. Most Linux distributions do not install all of these by default, but setting up a development environment is still straightforward.
Use the following commands to install the basic requirements for building Qt applications:
Debian/Ubuntu (apt-get)
Fedora/RHEL/CentOS (yum)
openSUSE (zypper)
Building Qt 5 from Source
You can also build Qt 5 from the source package and configure it according to your target platform. The source packages are obtained from http://www.qt.io/download/.
Below, you will find more information about building Qt from source.
Deployment and Other Issues
The pages below covers specific issues and recommendations for creating Linux/X11 applications.
Where to Go from Here
We invite you to explore the rest of Qt. We prepared overviews which help you decide which APIs to use and our examples demonstrate how to use our API.
- Qt Overviews — list of topics about application development
- Examples and Tutorials — code samples and tutorials
- Qt Reference Pages — a listing of C++ and QML APIs
- Qt X11 Extras — provides additional APIs for X11
Qt’s vibrant and active community site, http://qt.io houses a wiki, a forum, and additional learning guides and presentations.
В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
Источник
Qt/C++ — Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC
Первоначальное знакомство с Boost под Windows начну со сборки предкомпилированных библиотек и подключения их к проекту на Qt. При этом воспользуюсь кодом одного из Hello World-ов из документации Boost, а именно с установки locale с использованием boost.
Сборка Boost для MinGW
Вначале скачиваем последнюю версию Boost (на момент написания статьи это версия 1.61) и распаковываем архив в одну из папок. В моём случае архив был распакован по следующему пути:
После чего открываем консоль и переходим в эту папку. В данной папке имеется батник bootstrap.bat для сборки инструмента bjam, который предназначен для управления компиляцией библиотек под целевой компилятор.
Чтобы собрать данный инструмент для MinGW необходимо выполнить следующую команду:
После того, как инструмент будет собран выполняем сборку всех необходимых библиотек следующей командой:
Далее можно заняться своими делами, поскольку процесс этот не быстрый.
Примечание
Отмечу, что выбор компилятора, которым будут собраны библиотеки будет определяться тем, какие переменные окружения прописаны в вашей ОС. То есть от того, какой путь прописан к компилятору g++ в переменной PATH.
У меня от предыдущих версий Qt остались прописаны пути:
И соответственно на выходе я получил библиотеки для компилятора MinGW 4.9.2. Да, я не успел ещё удалить предыдущую версию Qt 5.6 с MinGW 4.9.2 . Надо ли говорить, что у меня проект под Qt5.7 с компилятором MinGW 5.3.0 отказался собираться?
Так что после прописывания правильных путей удалось собрать нужные библиотеки:
Сборка Boost для MSVC
Процесс будет полностью аналогичен тому, что и для MinGW, но с небольшой разницей в командах.
В процессе сборки могут возникнуть некоторые ошибки, которые также обусловлены путями в переменных ОС. Например такая:
Лечится прописыванием путей к компилятору MSVC, например:
Также могут возникнуть проблемы, что не будут находиться пути к заголовочным файлам стандартной библиотеки. Что будет выражено информацией в файле bootstrap.log :
Тоже потребуется некоторое шаманство с путями, либо даже переустановка MSVC, либо можно пойти по наиболее простому пути, который сэкономит нервные клетки, и просто скачать предкомпилированные библиотеки с сайта Boost-а.
Подключение Boost к Qt проекту
Для первоначального подключения Boost подготовим простое консольное приложение, которое будет выводить время, дату и ещё кое-какую информацию с использованием установки локали с помощью библиотеки Boost.locale.
Проект будет состоять всего из двух файлов:
QtBoostHello.pro
В зависимости от компилятора, осуществляем подключение необходимых заголовочных файлов и библиотек:
- INCLUDEPATH — подключаем заголовочные файлы
- LIBS — подключаем библиотеки
main.cpp
В функции main присутствует один из классов из библиотеки Boost — это generator. Глубоко копать не будем, нам же нужно просто запустить проект. Отметим лишь то, что он используется для установки локали, как видно из кода.
Также, для этого класса используется динамическая библиотека. Но не для всего функционала необходимы библиотеки, часть Boost — это шаблонные функции, которые полностью определены в заголовочных файлах.
На выходе получим результат, как на изображении ниже. Если поиграетесь с определением локали, то есть вместо «en_US.UTF-8» пропишите «ru_RU.UTF-8», то заметите, что дата и время поменяют формат, впрочем, как и валюта.
Рекомендуем хостинг TIMEWEB
Рекомендуемые статьи по этой тематике
Источник