[c++] How to use Boost in Visual Studio 2010

What is a good step by step explanation on how to use the Boost library in an empty project in Visual Studio?

This question is related to c++ visual-studio-2010 boost

The answer is


While the instructions on the Boost web site are helpful, here is a condensed version that also builds x64 libraries.

  • You only need to do this if you are using one of the libraries mentioned in section 3 of the instructions page. (E.g., to use Boost.Filesystem requires compilation.) If you are not using any of those, just unzip and go.

Build the 32-bit libraries

This installs the Boost header files under C:\Boost\include\boost-(version), and the 32-bit libraries under C:\Boost\lib\i386. Note that the default location for the libraries is C:\Boost\lib but you’ll want to put them under an i386 directory if you plan to build for multiple architectures.

  1. Unzip Boost into a new directory.
  2. Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
  3. Run: bootstrap
  4. Run: b2 toolset=msvc-12.0 --build-type=complete --libdir=C:\Boost\lib\i386 install

    • For Visual Studio 2012, use toolset=msvc-11.0
    • For Visual Studio 2010, use toolset=msvc-10.0
    • For Visual Studio 2017, use toolset=msvc-14.1
  5. Add C:\Boost\include\boost-(version) to your include path.

  6. Add C:\Boost\lib\i386 to your libs path.

Build the 64-bit libraries

This installs the Boost header files under C:\Boost\include\boost-(version), and the 64-bit libraries under C:\Boost\lib\x64. Note that the default location for the libraries is C:\Boost\lib but you’ll want to put them under an x64 directory if you plan to build for multiple architectures.

  1. Unzip Boost into a new directory.
  2. Start a 64-bit MSVC command prompt and change to the directory where Boost was unzipped.
  3. Run: bootstrap
  4. Run: b2 toolset=msvc-12.0 --build-type=complete --libdir=C:\Boost\lib\x64 architecture=x86 address-model=64 install
    • For Visual Studio 2012, use toolset=msvc-11.0
    • For Visual Studio 2010, use toolset=msvc-10.0
  5. Add C:\Boost\include\boost-(version) to your include path.
  6. Add C:\Boost\lib\x64 to your libs path.

Here is how I was able to use Boost:

  1. Download and extract the zip version of Boost libraries.
  2. Run bootstrap.bat file and then run bjam.exe.
  3. Wait for roughly 30 minutes or so.
  4. Create a new project in Visual Studio.
  5. Go to project-->properties-->Linker-->General-->Additional Library Directories and add boost/stage/lib directory to it.
  6. Go to project-->properties-->C/C++-->General-->Additional Include Directories and add boost directory to it.

You will be able to build your project without any errors !


Download boost from: http://www.boost.org/users/download/ e.g. by svn

  • Windows -> tortoise (the simplest way)

After that : cmd -> go to boost directory ("D:\boostTrunk" - where You checkout or download and extract package): command : bootstrap

we created bjam.exe in ("D:\boostTrunk") After that : command : bjam toolset=msvc-10.0 variant=debug,release threading=multi link=static (It will take some time ~20min.)

After that: Open Visual studio 2010 -> create empty project -> go to project properties -> set:

Project properties VS 2010

Paste this code and check if it is working?

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/regex.hpp>

using namespace std;

struct Hello 
{
    Hello(){ 
        cout << "Hello constructor" << endl;
    }

    ~Hello(){
        cout << "Hello destructor" << endl;
        cin.get();
    }
};


int main(int argc, char**argv)
{
    //Boost regex, compiled library
    boost::regex regex("^(Hello|Bye) Boost$");
    boost::cmatch helloMatches;
    boost::regex_search("Hello Boost", helloMatches, regex);
    cout << "The word between () is: " << helloMatches[1] << endl;

    //Boost shared pointer, header only library
    boost::shared_ptr<Hello> sharedHello(new Hello);

    return 0;
}

Resources : https://www.youtube.com/watch?v=5AmwIwedTCM


You can also try -j%NUMBER_OF_PROCESSORS% as an argument it will use all your cores. Makes things super fast on my quad core.


This thread has been around a while, and I thought I'd add something about HOW to build Boost as fast as possible on your specific hardware.

If you have a 4 or 6-core use -j5 or -j7 respectively. Certainly not the standard build nor -j2 unless you indeed have dual core.

I'm running a Sandy Bridge Extreme with stock clocked 3930K (6-core) on my main station, but have a 2600k (4-core) on older backup box, and the trend is I get the best Boost compile times with N + 1 build processes where N is the number of physical cores. N+2 reaches a point of diminishing returns and the times go up.

Notes: Hyperthreading is enabled, 32GB RAM DDR3, Samsung 840 EVO SSD.

-j7 on 6-core (2 minutes and 51 seconds) (Win7 Ultimate x64)(Visual Studio 2013)

PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j7 --build-type=complete msvc stage }

Days              : 0
Hours             : 0
Minutes           : 2
Seconds           : 51
Milliseconds      : 128
Ticks             : 1711281830
TotalDays         : 0.0019806502662037
TotalHours        : 0.0475356063888889
TotalMinutes      : 2.85213638333333
TotalSeconds      : 171.128183
TotalMilliseconds : 171128.183

-j6 on 6-core (3 minutes and 2 seconds) (Win7 Ultimate x64)(Visual Studio 2013)

PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j6 --build-type=complete msvc stage }

Days              : 0
Hours             : 0
Minutes           : 3
Seconds           : 2
Milliseconds      : 809
Ticks             : 1828093904
TotalDays         : 0.00211584942592593
TotalHours        : 0.0507803862222222
TotalMinutes      : 3.04682317333333
TotalSeconds      : 182.8093904
TotalMilliseconds : 182809.3904

-j8 on 6-core (3 minutes and 17 seconds) (Win7 Ultimate x64)(Visual Studio 2013)

PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j8 --build-type=complete msvc stage }

Days              : 0
Hours             : 0
Minutes           : 3
Seconds           : 17
Milliseconds      : 652
Ticks             : 1976523915
TotalDays         : 0.00228764342013889
TotalHours        : 0.0549034420833333
TotalMinutes      : 3.294206525
TotalSeconds      : 197.6523915
TotalMilliseconds : 197652.3915

-j7 build on 6-core

Config

Building the Boost C++ Libraries.


Performing configuration checks

    - 32-bit                   : yes (cached)
    - arm                      : no  (cached)
    - mips1                    : no  (cached)
    - power                    : no  (cached)
    - sparc                    : no  (cached)
    - x86                      : yes (cached)
    - has_icu builds           : no  (cached)
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
    - zlib                     : no  (cached)
    - iconv (libc)             : no  (cached)
    - iconv (separate)         : no  (cached)
    - icu                      : no  (cached)
    - icu (lib64)              : no  (cached)
    - message-compiler         : yes (cached)
    - compiler-supports-ssse3  : yes (cached)
    - compiler-supports-avx2   : yes (cached)
    - gcc visibility           : no  (cached)
    - long double support      : yes (cached)
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
    - zlib                     : no  (cached)

I note the 64-bit build takes a bit longer, I need to do the same comparison for those and update.


Also a little note: If you want to reduce the compilation-time, you can add the flag

-j2

to run two parallel builds at the same time. This might reduce it to viewing one movie ;)


I could recommend the following trick: Create a special boost.props file

  1. Open the property manager
  2. Right click on your project node, and select 'Add new project property sheet'.
  3. Select a location and name your property sheet (e.g. c:\mystuff\boost.props)
  4. Modify the additional Include and Lib folders to the search path.

This procedure has the value that boost is included only in projects where you want to explicitly include it. When you have a new project that uses boost, do:

  1. Open the property manager.
  2. Right click on the project node, and select 'Add existing property sheet'.
  3. Select the boost property sheet.

EDIT (following edit from @jim-fred):

The resulting boost.props file looks something like this...

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros">
    <BOOST_DIR>D:\boost_1_53_0\</BOOST_DIR>
  </PropertyGroup>
  <PropertyGroup>
    <IncludePath>$(BOOST_DIR);$(IncludePath)</IncludePath>
    <LibraryPath>$(BOOST_DIR)stage\lib\;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
</Project>

It contains a user macro for the location of the boost directory (in this case, D:\boost_1_53_0) and two other parameters: IncludePath and LibraryPath. A statement #include <boost/thread.hpp> would find thread.hpp in the appropriate directory (in this case, D:\boost_1_53_0\boost\thread.hpp). The 'stage\lib\' directory may change depending on the directory installed to.

This boost.props file could be located in the D:\boost_1_53_0\ directory.


A minimalist example to get you started in Visual Studio:

1.Download and unzip Boost from here.

2.Create a Visual Studio empty project, using an example boost library that does not require separate compilation:

#include <iostream>
#include <boost/format.hpp>

using namespace std;  
using namespace boost;  

int main()  
{  
    unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };  

    cout << format("%02X-%02X-%02X-%02X-%02X")  
            % arr[0]  
            % arr[1]  
            % arr[2]  
            % arr[3]  
            % arr[4]  
         << endl;  
}  

3.In your Visual Studio project properties set the Additional Include Directories:

Project Properties

For a very simple example:

How to Install the Boost Libraries in Visual Studio

If you don't want to use the entire boost library, just a subset:

Using a subset of the boost libraries in Windows

If you specifically want to now about the libraries that require compilation:

How to use the Boost compiled libraries in Windows


What parts of Boost do you need? A lot of stuff is part of TR1 which is shipped with Visual Studio, so you could simply say, for example:

#include <tr1/memory>

using std::tr1::shared_ptr;

According to James, this should also work (in C++0x):

#include <memory>

using std::shared_ptr;

The Windows installers located here worked perfectly for me. I took the following steps:

  1. Follow the installation wizard until finished.
  2. Run visual studio.
  3. Create a new C++ project
  4. Open project properties (can be found by right-clicking the project name in the solution explorer)
  5. Under "C/C++ > General > Additional Include Directories" add the path where boost root directory. Default for my version was C:\local\boost_1_63_0. The number after "boost" is the version of boost.
  6. In project properties, under "Linker > Additional Library Directories" add the directory for library files. Default for my version was C:\local\boost_1_63_0\lib64-msvc-14.0. The number after "lib" is related to the build target (32 bit or 64 bit in Visual Studio) and the number after "msvc" is related to the version of Visual Studio (14.0 is related to Visual Studio 2015, but I'm using it with the 2017 Visual Studio).

Good luck!


In addition, there is something I find very useful. Use environment variables for your boost paths. (How to set environment variables in windows, link at bottom for 7,8,10) The BOOST_ROOT variable seems to be common place anymore and is set to the root path where you unzip boost.

Then in Properties, c++, general, Additional Include Directories use $(BOOST_ROOT). Then if/when you move to a newer version of the boost library you can update your environment variable to point to this newer version. As more of your projects, use boost you will not have to update the 'Additional Include Directories' for all of them.

You may also create a BOOST_LIB variable and point it to where the libs are staged. So likewise for the Linker->Additional Library Directories, you won't have to update projects. I have some old stuff built with vs10 and new stuff with vs14 so built both flavors of the boost lib to the same folder. So if I move a project from vs10 to vs14 I don't have to change the boost paths.

NOTE: If you change an environment variable it will not suddenly work in an open VS project. VS loads variables on startup. So you will have to close VS and reopen it.


A small addition to KTC's very informative main answer:

If you are using the free Visual Studio c++ 2010 Express, and managed to get that one to compile 64-bits binaries, and now want to use that to use a 64-bits version of the Boost libaries, you may end up with 32-bits libraries (your mileage may vary of course, but on my machine this is the sad case).

I could fix this using the following: inbetween the steps described above as

  1. Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
  2. Run: bootstrap

I inserted a call to 'setenv' to set the environment. For a release build, the above steps become:

  1. Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
  2. Run: "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\setenv.cmd" /Release /x64
  3. Run: bootstrap

I found this info here: http://boost.2283326.n4.nabble.com/64-bit-with-VS-Express-again-td3044258.html


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to visual-studio-2010

variable is not declared it may be inaccessible due to its protection level SSIS Excel Connection Manager failed to Connect to the Source This project references NuGet package(s) that are missing on this computer Gridview get Checkbox.Checked value error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop? Attach (open) mdf file database with SQL Server Management Studio What is and how to fix System.TypeInitializationException error? Could not load file or assembly "Oracle.DataAccess" or one of its dependencies IIS error, Unable to start debugging on the webserver

Examples related to boost

CMake is not able to find BOOST libraries version `CXXABI_1.3.8' not found (required by ...) Already defined in .obj - no double inclusions C++ Boost: undefined reference to boost::system::generic_category() fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib' How to install Boost on Ubuntu Calculate rolling / moving average in C++ undefined reference to boost::system::system_category() when compiling Calculate mean and standard deviation from a vector of samples in C++ using Boost Get current time in milliseconds using C++ and Boost