Как установить boost c
Перейти к содержимому

Как установить boost c

  • автор:

Сборка boost. Шпаргалка

На странице очень кратко описан процесс сборки boost. Тем, кто знаком с процессом сбоки boost, статья может быть полезна в качестве шпаргалки или источника для копипасты. Начинающие могут рассматривать эту страницу как дополнительный материал к другим источникам. Не стоит рассматривать эту статью как основной источник информации по этой теме.

Сборка boost под Windows и Linux

Процесс сборки библиотеки boost для ОС Windows и Linux существенно не отличается, за исключением указания компилятора на ОС Windows. Далее кратко описаны необходимые шаги:

  • Скачать дистрибутив с официального сайта.
  • Распаковать в любую директорию, условно, .
  • cd.
  • Выполнить bootstrap.bat или bootstrap.sh . Для Windows при необходимости добавить аргумент gcc.
  • Почитать b2 —help, если интересно, как использовать билдер boost (b2).
  • Сборка.

Примеры команд для сборки boost под mingw:

b2 toolset=gcc link=shared --prefix=C:/boost install b2 toolset=gcc threading=multi link=static runtime-link=shared --prefix=C:/boost install b2 --build-type=complete toolset=gcc threading=multi link=static runtime-link=shared stage

Примеры команд для сборки boost под Visual C++:

b2 toolset=msvc variant=debug link=shared threading=multi runtime-link=shared stage b2 toolset=vc140 link=static threading=multi runtime-link=shared address-model=32 install
Сборка кросс-компилятором под ARM
  • Скачать и распаковать.
  • Запустить bootstrab.sh .
  • Открыть project-config.jam, заменить «using gcc» на «using gcc : arm : arm-linux-gnueabihf-g++».
  • Добавить путь к тулчейну в переменную PATH (если не сделано).
  • В командной строке b2 указать: toolset=gcc-arm cxxflags=»-std=c++11″.
  • Сборка.

Итоговая строка b2 будет выглядеть так:

./b2 toolset=gcc-arm cxxflags="-std=c++11" --prefix=/home/user/boost-arm/ stage install

Примечание: флаг cxxflags background-color: inherit; color: inherit; font-family: inherit; font-size: 1rem;»>++11″ в некоторых случаях может помочь при компоновке boost::log.

Замечания о стаической компоновке

По какой-то причине на дистрибутивах с архитектурой x86_64 статические библиотеки, устанавливаемые через пакетный менеджер из репозиториев, собраны без флага -fPIC. Это не позволяет осуществлять статическую компоновку библиотеки к динамической библиотеке, что иногда бывает нужно. Для решения проблемы приходится пересобирать библиотеки с указанием флага -fPIC. Кроме того, крайне желательно явно указать стандарт языка при сборке библиотек. Следовательно, команда сборки библиотек Boost может выглядеть так:

./b2 link=static threading=multi cxxflags="-fPIC -std=c++11" install --prefix=/path-to-install

Отдельное слово про Boost::log: с этой библиотекой часто возникают различные проблемы при сборке. Уйма времени потрачена на то, чтобы понять, почему эта библиотека не работает / не компонуется на той или иной платформе и как вывод во многих случаях лучшим решением было просто отказаться от нее.

Boost.Asio C++ Tutorial

Тем, кто не знает, что такое Boost.Asio, посвящается. Boost.Asio — это кросс-платформенная библиотека С++ для сетевого и низкоуровневого ввода-вывода программирования, которая предоставляет разработчикам, использующим асинхронную модель, современный подход программирования на С++. В нашем случае это будет С++11.

Версия Boost, которую я использую — Boost Version 1.60.0. Скачать можно тут.

Опираясь на свой опыт, хотелось бы сразу решить вопрос с установкой библиотеки. Я использую MVS 15, следовательно ставить Boost мы будем туда.

Установка библиотеки

  • После скачивания архива с библиотекой, распаковываем его на Локальный диск (лучше) С.
  • Открываем папку boost_1_60_0 и запускаем файл bootstrap.bat
  • После того как bootstrap.bat отработает, в папке появится файл b2.exe
  • Запускаем b2.exe и ждем от 5 минут до 1,5 часа (зависит от «машины»)
  • Когда b2.exe отработает, ваша библиотека будет в собранном состоянии, осталось только её подключить в нашу IDE.
  • Запускаем MVS, в вкладке «Вид» находим Property Manager
  • Двойным кликом открываем страницу свойств папки Debug | Win32 и кликаем на VC++ Directories
  • В колонке Include Directories выбираем изменить, далее нажимаем на «папку со *» New Line и указываем ей путь к папке boost_1_60_0, жмём ОК.
  • Проводим аналогию с некоторыми изменениями для колонки Library Directoties, но для неё указываем путь C:\boost_1_60_0\stage\lib, жмём ОК.
  • Библиотека подключена!

Basic Skills

Первые пять уроков, или как они называются в учебнике Timer, будут вводными в фундаментальные понятия, необходимые для использования инструмента Asio. Перед тем, как погрузиться в сложный мир сетевого программирования, эти Timers (уроки) иллюстрируют базовые навыки, используя простые асинхронные таймеры.

Урок 1. — Использование синхронного таймера. «Timer.1 — Using a timer synchronously«

Этот урок вводит нас в Asio, показывая, как выполняется ожидание по таймеру. Начнём мы с подключения заголовочных файлов. Все Asio классы представлены в виде файлов с расширением Asio.hpp.

#include #include 

Так как в этом примере мы используем таймеры, то мы должны включить соответствующий файл заголовка Boost.Date_Time.

#include 

Все программы, которые используют Asio, должны иметь, по крайней мере, один объект io_service. Этот класс обеспечивает доступ к функциям ввода / вывода. Мы объявляем объект этого типа первым делом в главной функции. Но перед этим я хотел бы немного облегчить написание нашего кода, при помощи пространства имени. После всех подключенных ЗФ, пишем:

using namespace std; using namespace boost::asio; 

Думаю тут особо вопросов не должно возникнуть.

int main() < io_service io; 

Далее мы объявляем объект типа deadline_timer. Основные классы Asio, которые обеспечивают функции ввода/вывода (или как в данном случае функциональность нашего Таймера) всегда берут ссылку на io_service в качестве первого аргумента конструктора. Второй аргумент конструктора установка таймера 5 секунд.

deadline_timer t(io, boost::posix_time::seconds(5)); 

В этом простом примере мы выполняем блокирующие ожидание по таймеру. То есть, вызов deadline_timer :: wait () не вернется, пока таймер не отсчитает 5 секунд после того, как он был создан. Deadline timer, всегда находится в одном из двух состояний: «истек»(expired)или «не истек»(not expired). Если deadline_timer::wait() функция принимает аргумент expired, то функция сразу же вернёт значение.

t.wait(); 

Наконец мы выводим всеми любимый и знакомый «Hello, World!» сообщение, чтобы показать, когда таймер истек «expired».

 cout 

Полный код программы в оригинале:

#include #include #include int main()

Полный код программы в личном варианте:

#include #include #include using namespace std; using namespace boost::asio; int main()

Boost Getting Started on Windows

If you plan to use your tools from the Windows command prompt, you're in the right place. If you plan to build from the Cygwin bash shell, you're actually running on a POSIX platform and should follow the instructions for getting started on Unix variants. Other command shells, such as MinGW's MSYS, are not supported—they may or may not work.

  • 1 Get Boost
  • 2 The Boost Distribution
  • 3 Header-Only Libraries
  • 4 Build a Simple Program Using Boost
    • 4.1 Build From the Visual Studio IDE
    • 4.2 Or, Build From the Command Prompt
    • 4.3 Errors and Warnings
    • 5.1 Simplified Build From Source
    • 5.2 Or, Build Binaries From Source
      • 5.2.1 Install Boost.Build
      • 5.2.2 Identify Your Toolset
      • 5.2.3 Select a Build Directory
      • 5.2.4 Invoke b2
      • 6.1 Link From Within the Visual Studio IDE
      • 6.2 Or, Link From the Command Prompt
      • 6.3 Library Naming
      • 6.4 Test Your Program

      1 Get Boost

      The most reliable way to get a copy of Boost is to download boost_1_82_0.7z or boost_1_82_0.zip and unpack it to install a complete Boost distribution. 1

      2 The Boost Distribution

      This is a sketch of the resulting directory structure:

      boost_1_82_0\ . The “boost root directory” index.htm . A copy of www.boost.org starts here boost\ . All Boost Header files lib\ . precompiled library binaries libs\ . Tests, .cpps, docs, etc., by library index.html . Library documentation starts here algorithm\ any\ array\ …more libraries… status\ . Boost-wide test suite tools\ . Utilities, e.g. Boost.Build, quickbook, bcp more\ . Policy documents, etc. doc\ . A subset of all Boost library docs 

      The organization of Boost library headers isn't entirely uniform, but most libraries follow a few patterns:

      • Some older libraries and most very small libraries place all public headers directly into boost\.
      • Most libraries' public headers live in a subdirectory of boost\, named after the library. For example, you'll find the Python library's def.hpp header in

      boost\python\def.hpp.
      boost\python.hpp.

      It's important to note the following:

      1. The path to the boost root directory (often C:\Program Files\boost\boost_1_82_0) is sometimes referred to as $BOOST_ROOT in documentation and mailing lists .
      2. To compile anything in Boost, you need a directory containing the boost\ subdirectory in your #include path. Specific steps for setting up #include paths in Microsoft Visual Studio follow later in this document; if you use another IDE, please consult your product's documentation for instructions.
      3. Since all of Boost's header files have the .hpp extension, and live in the boost\ subdirectory of the boost root, your Boost #include directives will look like:

      #include whatever.hpp>
      #include "boost/whatever.hpp"

      3 Header-Only Libraries

      The first thing many people want to know is, “how do I build Boost?” The good news is that often, there's nothing to build.

      Nothing to Build?

      Most Boost libraries are header-only: they consist entirely of header files containing templates and inline functions, and require no separately-compiled library binaries or special treatment when linking.

      The only Boost libraries that must be built separately are:

      • Boost.Chrono
      • Boost.Context
      • Boost.Filesystem
      • Boost.GraphParallel
      • Boost.IOStreams
      • Boost.Locale
      • Boost.Log (see build documentation)
      • Boost.MPI
      • Boost.ProgramOptions
      • Boost.Python (see the Boost.Python build documentation before building and installing it)
      • Boost.Regex
      • Boost.Serialization
      • Boost.Thread
      • Boost.Timer
      • Boost.Wave

      A few libraries have optional separately-compiled binaries:

      • Boost.Graph also has a binary component that is only needed if you intend to parse GraphViz files.
      • Boost.Math has binary components for the TR1 and C99 cmath functions.
      • Boost.Random has a binary component which is only needed if you're using random_device.
      • Boost.Test can be used in “header-only” or “separately compiled” mode, although separate compilation is recommended for serious use.
      • Boost.Exception provides non-intrusive implementation of exception_ptr for 32-bit _MSC_VER==1310 and _MSC_VER==1400 which requires a separately-compiled binary. This is enabled by #define BOOST_ENABLE_NON_INTRUSIVE_EXCEPTION_PTR.
      • Boost.System is header-only since Boost 1.69. A stub library is still built for compatibility, but linking to it is no longer necessary.

      4 Build a Simple Program Using Boost

      To keep things simple, let's start by using a header-only library. The following program reads a sequence of integers from standard input, uses Boost.Lambda to multiply each number by three, and writes them to standard output:

      #include #include #include #include int main() < using namespace boost::lambda; typedef std::istream_iteratorin; std::for_each( in(std::cin), in(), std::cout

      Copy the text of this program into a file called example.cpp.

      To build the examples in this guide, you can use an Integrated Development Environment (IDE) like Visual Studio, or you can issue commands from the command prompt. Since every IDE and compiler has different options and Microsoft's are by far the dominant compilers on Windows, we only give specific directions here for Visual Studio 2005 and .NET 2003 IDEs and their respective command prompt compilers (using the command prompt is a bit simpler). If you are using another compiler or IDE, it should be relatively easy to adapt these instructions to your environment.

      Command Prompt Basics

      In Windows, a command-line tool is invoked by typing its name, optionally followed by arguments, into a Command Prompt window and pressing the Return (or Enter) key.

      To open a generic Command Prompt, click the Start menu button, click Run, type “cmd”, and then click OK.

      All commands are executed within the context of a current directory in the filesystem. To set the current directory, type:

      cd path\to\some\directory 

      followed by Return. For example,

      cd C:\Program Files\boost\boost_1_82_0 

      Long commands can be continued across several lines by typing a caret (^) at the end of all but the last line. Some examples on this page use that technique to save horizontal space.

      4.1 Build From the Visual Studio IDE

      • From Visual Studio's File menu, select New >Project…
      • In the left-hand pane of the resulting New Project dialog, select Visual C++ >Win32.
      • In the right-hand pane, select Win32 Console Application (VS8.0) or Win32 Console Project (VS7.1).
      • In the name field, enter “example”
      • Right-click example in the Solution Explorer pane and select Properties from the resulting pop-up menu
      • In Configuration Properties >C/C++ >General >Additional Include Directories, enter the path to the Boost root directory, for example

      C:\Program Files\boost\boost_1_82_0

      To test your application, hit the F5 key and type the following into the resulting window, followed by the Return key:

      1 2 3

      Then hold down the control key and press "Z", followed by the Return key.

      4.2 Or, Build From the Command Prompt

      From your computer's Start menu, if you are a Visual Studio 2005 user, select

      All Programs > Microsoft Visual Studio 2005 > Visual Studio Tools > Visual Studio 2005 Command Prompt

      or, if you're a Visual Studio .NET 2003 user, select

      All Programs > Microsoft Visual Studio .NET 2003 > Visual Studio .NET Tools > Visual Studio .NET 2003 Command Prompt

      to bring up a special command prompt window set up for the Visual Studio compiler. In that window, set the current directory to a suitable location for creating some temporary files and type the following command followed by the Return key:

      cl /EHsc /I path\to\boost_1_82_0 path\to\example.cpp

      To test the result, type:

      echo 1 2 3 | example

      4.3 Errors and Warnings

      Don't be alarmed if you see compiler warnings originating in Boost headers. We try to eliminate them, but doing so isn't always practical. 4 Errors are another matter. If you're seeing compilation errors at this point in the tutorial, check to be sure you've copied the example program correctly and that you've correctly identified the Boost root directory.

      5 Prepare to Use a Boost Library Binary

      If you want to use any of the separately-compiled Boost libraries, you'll need to acquire library binaries.

      5.1 Simplified Build From Source

      If you wish to build from source with Visual C++, you can use a simple build procedure described in this section. Open the command prompt and change your current directory to the Boost root directory. Then, type the following commands:

      bootstrap .\b2

      The first command prepares the Boost.Build system for use. The second command invokes Boost.Build to build the separately-compiled Boost libraries. Please consult the Boost.Build documentation for a list of allowed options.

      5.2 Or, Build Binaries From Source

      If you're using an earlier version of Visual C++, or a compiler from another vendor, you'll need to use Boost.Build to create your own binaries.

      5.2.1 Install Boost.Build

      Boost.Build is a text-based system for developing, testing, and installing software. First, you'll need to build and install it. To do this:

      1. Go to the directory tools\build\.
      2. Run bootstrap.bat
      3. Run b2 install --prefix=PREFIX where PREFIX is the directory where you want Boost.Build to be installed
      4. Add PREFIX\bin to your PATH environment variable.

      5.2.2 Identify Your Toolset

      First, find the toolset corresponding to your compiler in the following table (an up-to-date list is always available in the Boost.Build documentation).

      If you previously chose a toolset for the purposes of building b2, you should assume it won't work and instead choose newly from the table below.

      Toolset Name Vendor Notes
      acc Hewlett Packard Only very recent versions are known to work well with Boost
      borland Borland
      como Comeau Computing Using this toolset may require configuring another toolset to act as its backend.
      darwin Apple Computer Apple's version of the GCC toolchain with support for Darwin and MacOS X features such as frameworks.
      gcc The Gnu Project Includes support for Cygwin and MinGW compilers.
      hp_cxx Hewlett Packard Targeted at the Tru64 operating system.
      intel Intel
      msvc Microsoft
      sun Oracle Only very recent versions are known to work well with Boost. Note that the Oracle/Sun compiler has a large number of options which effect binary compatibility: it is vital that the libraries are built with the same options that your appliction will use. In particular be aware that the default standard library may not work well with Boost, unless you are building for C++11. The particular compiler options you need can be injected with the b2 command line options cxxflags=``and ``linkflags=. For example to build with the Apache standard library in C++03 mode use b2 cxxflags=-library=stdcxx4 linkflags=-library=stdcxx4 .
      vacpp IBM The VisualAge C++ compiler.

      If you have multiple versions of a particular compiler installed, you can append the version number to the toolset name, preceded by a hyphen, e.g. intel-9.0 or borland-5.4.3 . On Windows, append a version number even if you only have one version installed (unless you are using the msvc or gcc toolsets, which have special version detection code) or auto-linking will fail.

      5.2.3 Select a Build Directory

      Boost.Build will place all intermediate files it generates while building into the build directory. If your Boost root directory is writable, this step isn't strictly necessary: by default Boost.Build will create a bin.v2/ subdirectory for that purpose in your current working directory.

      5.2.4 Invoke b2

      Change your current directory to the Boost root directory and invoke b2 as follows:

      b2 --build-dir=build-directory toolset=toolset-name --build-type=complete stage

      For a complete description of these and other invocation options, please see the Boost.Build documentation.

      For example, your session might look like this: 3

      C:\WINDOWS> cd C:\Program Files\boost\boost_1_82_0 C:\Program Files\boost\boost_1_82_0> b2 ^ More? --build-dir="C:\Documents and Settings\dave\build-boost" ^ More? --build-type=complete msvc stage

      Be sure to read this note about the appearance of ^, More? and quotation marks (") in that line.

      The option “--build-type=complete” causes Boost.Build to build all supported variants of the libraries. For instructions on how to build only specific variants, please ask on the Boost Users' mailing list.

      Building the special stage target places Boost library binaries in the stage\lib\ subdirectory of the Boost tree. To use a different directory pass the --stagedir= directory option to b2.

      b2 is case-sensitive; it is important that all the parts shown in bold type above be entirely lower-case.

      For a description of other options you can pass when invoking b2, type:

      b2 --help

      In particular, to limit the amount of time spent building, you may be interested in:

      • reviewing the list of library names with --show-libraries
      • limiting which libraries get built with the --with-library-name or --without-library-name options
      • choosing a specific build variant by adding release or debug to the command line.

      Boost.Build can produce a great deal of output, which can make it easy to miss problems. If you want to make sure everything is went well, you might redirect the output into a file by appending “>build.log 2>&1 ” to your command line.

      5.3 Expected Build Output

      During the process of building Boost libraries, you can expect to see some messages printed on the console. These may include

      • Notices about Boost library configuration—for example, the Regex library outputs a message about ICU when built without Unicode support, and the Python library may be skipped without error (but with a notice) if you don't have Python installed.
      • Messages from the build tool that report the number of targets that were built or skipped. Don't be surprised if those numbers don't make any sense to you; there are many targets per library.
      • Build action messages describing what the tool is doing, which look something like:

      toolset-name.c++ long/path/to/file/being/built 

      5.4 In Case of Build Errors

      The only error messages you see when building Boost—if any—should be related to the IOStreams library's support of zip and bzip2 formats as described here. Install the relevant development packages for libz and libbz2 if you need those features. Other errors when building Boost libraries are cause for concern.

      If it seems like the build system can't find your compiler and/or linker, consider setting up a user-config.jam file as described here. If that isn't your problem or the user-config.jam file doesn't work for you, please address questions about configuring Boost for your compiler to the Boost Users' mailing list.

      6 Link Your Program to a Boost Library

      To demonstrate linking with a Boost binary library, we'll use the following simple program that extracts the subject lines from emails. It uses the Boost.Regex library, which has a separately-compiled binary component.

      #include #include #include int main() < std::string line; boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" ); while (std::cin) < std::getline(std::cin, line); boost::smatch matches; if (boost::regex_match(line, matches, pat)) std::cout >

      There are two main challenges associated with linking:

      1. Tool configuration, e.g. choosing command-line options or IDE build settings.
      2. Identifying the library binary, among all the build variants, whose compile configuration is compatible with the rest of your project.

      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.

      6.1 Link From Within the Visual Studio IDE

      Starting with the header-only example project we created earlier:

      1. Right-click example in the Solution Explorer pane and select Properties from the resulting pop-up menu
      2. In Configuration Properties >Linker >Additional Library Directories, enter the path to the Boost binaries, e.g. C:\Program Files\boost\boost_1_82_0\lib\.
      3. From the Build menu, select Build Solution.

      6.2 Or, Link From the Command Prompt

      For example, we can compile and link the above program from the Visual C++ command-line by simply adding the bold text below to the command line we used earlier, assuming your Boost binaries are in C:\Program Files\boost\boost_1_82_0\lib:

      cl /EHsc /I path\to\boost_1_82_0 example.cpp ^ /link /LIBPATH:C:\Program Files\boost\boost_1_82_0\lib 

      6.3 Library Naming

      If, like Visual C++, your compiler supports auto-linking, you can probably skip to the next step.

      In order to choose the right binary for your build configuration you need to know how Boost binaries are named. Each library filename is composed of a common sequence of elements that describe how it was built. For example, libboost_regex-vc71-mt-d-x86-1_34.lib can be broken down into the following elements:

      lib Prefix: except on Microsoft Windows, every Boost library name begins with this string. On Windows, only ordinary static libraries use the lib prefix; import libraries and DLLs do not. 5 boost_regex Library name: all boost library filenames begin with boost_. -vc71 Toolset tag: identifies the toolset and version used to build the binary. -mt Threading tag: indicates that the library was built with multithreading support enabled. Libraries built without multithreading support can be identified by the absence of -mt . -d

      ABI tag: encodes details that affect the library's interoperability with other compiled code. For each such feature, a single letter is added to the tag:

      Key Use this library when: Boost.Build option
      s linking statically to the C++ standard library and compiler runtime support libraries. runtime-link=static
      g using debug versions of the standard and runtime support libraries. runtime-debugging=on
      y using a special debug build of Python. python-debugging=on
      d building a debug version of your code. 6 variant=debug
      p using the STLPort standard library rather than the default one supplied with your compiler. stdlib=stlport

      For example, if you build a debug version of your code for use with debug versions of the static runtime library and the STLPort standard library, the tag would be: -sgdp . If none of the above apply, the ABI tag is ommitted.

      Architecture and address model tag: in the first letter, encodes the architecture as follows:

      Key Architecture Boost.Build option
      x x86-32, x86-64 architecture=x86
      a ARM architecture=arm
      i IA-64 architecture=ia64
      s Sparc architecture=sparc
      m MIPS/SGI architecture=mips*
      p RS/6000 & PowerPC architecture=power

      The two digits following the letter encode the address model as follows:

      Key Address model Boost.Build option
      32 32 bit address-model=32
      64 64 bit address-model=64

      -1_34 Version tag: the full Boost release number, with periods replaced by underscores. For example, version 1.31.1 would be tagged as "-1_31_1". .lib Extension: determined according to the operating system's usual convention. On most unix-style platforms the extensions are .a and .so for static libraries (archives) and shared libraries, respectively. On Windows, .dll indicates a shared library and .lib indicates a static or import library. Where supported by toolsets on unix variants, a full version extension is added (e.g. ".so.1.34") and a symbolic link to the library file, named without the trailing version number, will also be created.

      6.4 Test Your Program

      To test our subject extraction, we'll filter the following text file. Copy it out of your browser and save it as jayne.txt:

      To: George Shmidlap From: Rita Marlowe Subject: Will Success Spoil Rock Hunter? --- See subject.

      Now, in a command prompt window, type:

      path\to\compiled\example < path\to\jayne.txt

      The program should respond with the email subject, “Will Success Spoil Rock Hunter?”

      7 Conclusion and Further Resources

      This concludes your introduction to Boost and to integrating it with your programs. As you start using Boost in earnest, there are surely a few additional points you'll wish we had covered. One day we may have a “Book 2 in the Getting Started series” that addresses them. Until then, we suggest you pursue the following resources. If you can't find what you need, or there's anything we can do to make this document clearer, please post it to the Boost Users' mailing list.

      • Boost.Build reference manual
      • Boost Users' mailing list
      • Index of all Boost library documentation

      Good luck, and have fun!

      —the Boost Developers

      [1] We recommend downloading boost_1_82_0.7z and using 7-Zip to decompress it. We no longer recommend .zip files for Boost because they are twice as large as the equivalent .7z files. We don't recommend using Windows' built-in decompression as it can be painfully slow for large archives.
      [2] There's no problem using Boost with precompiled headers; these instructions merely avoid precompiled headers because it would require Visual Studio-specific changes to the source code used in the examples.
      [3]

      In this example, the caret character ^ is a way of continuing the command on multiple lines, and must be the final character used on the line to be continued (i.e. do not follow it with spaces). The command prompt responds with More? to prompt for more input. Feel free to omit the carets and subsequent newlines; we used them so the example would fit on a page of reasonable width.

      The command prompt treats each bit of whitespace in the command as an argument separator. That means quotation marks (") are required to keep text together whenever a single command-line argument contains spaces, as in

      --build-dir="C:\Documents_and_Settings\dave\build-boost" 

      Also, for example, you can't add spaces around the = sign as in

      --build-dir_=_"C:\Documents and Settings\dave\build-boost"

      Как установить библиотеку boost?

      Доброго времени суток. Нужна помощь!
      Хочу установить библиотеку boost. Во всех туториалах люди заходят в консольку Visual Studio Command Prompt (2010). Но проблема в том, что я не могу ее найти! Искать в винде пробовал - не нашел.
      У меня экспресс-версия! Дело в этом?

      Отслеживать
      51.2k 86 86 золотых знаков 266 266 серебряных знаков 505 505 бронзовых знаков
      задан 19 окт 2014 в 16:17
      65 1 1 золотой знак 1 1 серебряный знак 4 4 бронзовых знака

      3 ответа 3

      Сортировка: Сброс на вариант по умолчанию

      Библиотека boost - это набор частично компилируемых исходных кодов. В некоторых случаях ничего не нужно собирать, достаточно скачать с официального сайта дистрибутив, разместить в удобном месте и в настройках проекта указать пути.

      У меня в специальной папке, где я храню библиотеки многоразового использования, лежит подпапка boost_1_56_0 . Рядом с нею еще ряд других более старых версий этой библиотеки.

      В переменные среды (в windows это там же, где и PATH) я заношу переменную BOOST_ROOT , которая указывает на последнюю сборку. Т.е. как появится новая, я создам папку boost_1_XX_Y и переназначу эту переменную.

      В настройках любых проектов мне достаточно указать $(BOOST_ROOT)\include - для доступа к headers, и $(BOOST_ROOT)\stage\lib32 / $(BOOST_ROOT)\stage\lib64 для доступа к конкретным библиотекам, нужной мне разрядности.

      Поскольку boost автоматически выдает имена собираемым библиотекам, с учетом компиляторов, которыми они собираются, даже если у Вас разные компиляторы, бинарники удобно сбрасывать в одну папку, как указано выше.

      • С Intel Compiler у Вас получатся libboost_name-iw-type-version.lib .
      • С Visual Studio у Вас получатся libboost_name-vcXX-type-version.lib , где XX - версия компилятора visual studio (не студии, а именно компилятора).
      • С MinGW с gcc у Вас получится libboost_name-gcc-type-version.lib , если мне не изменяет память.

      При этом для сборки библиотек, которые необходимо собирать, необходимо выполнить одни и те же действия в консоли:

      • Для Intel Compiler это будет в соответствующем Command Prompt.
      • Для Visual Studio это будет в соответствующем Command Prompt.
      • Для MinGW это будет в обычной консоли, если, конечно, путь к bin в MinGW у Вас добавлен в переменную среды PATH.

      Действия надо выполнить одни и те же. Сначала bootstrap.bat , а потом b2 --help .

      В хелпе b2 Вы увидите все варианты настройки сборки, чтобы собрать наиболее удобным Вам образом.

      Строчка будет выглядеть так:

      b2 параметр1 параметр2 параметр3 .

      • toolset - его стоит указать, чтобы сборка производилась конкретным компилятором (gcc, intel, visual studio), причем можно указать и версию компилятора.
      • variant, вид сборки, debug или release. Для разработки Вам понадобятся оба варианта.
      • link - Вы выбираете, будет Ваш бинарный код обращаться в dll или содержать "в себе" все используемые алгоритмы.
      • threading - честно говоря, плохо понимаю смысл этой директивы и всегда указываю multi. Редко мы пишем однопоточные приложения.
      • runtime-link - то же, что и link, только для рантайма.
      • address-model - параметр не указан в хелпе, но помогает выбрать архитектуру собираемых библиотек.
      • stage/install, отличаются лишь тем, что install позволит "выгрузить" только нужное в отдельную папку, stage собирает всё туда, где оно есть. Если Вы не увлекаетесь изменениями исходников boost, stage Вам вполне подойдет.

      В итоге получается что-то вроде вот такого:

      b2 toolset=vc120 variant=debug link=shared threading=multi runtime-link=shared address-model=32 stage 

      Для дебага в x32 и такого:

      b2 toolset=vc120 variant=release link=static threading=multi runtime-link=shared address-model=32 stage 

      Для релиза в x32.

      Ждете около 40 минут, радуетесь результату. В случае проблем - гуглите, скорее всего уже тысячи людей сталкивались с Вашей проблемой, и ее решение - невнимательность или какие-то специфические настройки чего-нибудь. Например, при сборке boost python вылезает много warning-ов на MinGW из-за конфликта хедеров, подобные вещи можно разрулить в частном порядке.

      Потратив 2 часа на то, чтобы один раз в этом разобраться, Вы никогда не будете зависеть ни от каких сторонних сборок, будете понимать, где у Вас что лежит, кто туда положил и т.п. В общем, это полезно.

      ЗЫ: Command Prompt находится в Visual Studio Tools. Или посмотрите в VStudio_PATH\CommonXX\Tools\VsDevCmd.bat

      Добавить комментарий

      Ваш адрес email не будет опубликован. Обязательные поля помечены *