Install Boost library on Windows 11

Boost library download and installation

Boost official website address: https://www.boost.org/  , first go to the official website to download the corresponding version of the Boost library file. Click Download in the green box as shown below  to enter the download page. 

Enter the download page and download the required version. The version I am downloading now is 1.83.0 and the windows version boost_1_83_0.7z. 

 

Boost library installation 

After decompressing the downloaded file package, it looks like the following figure:

Knowledge expansion: Windows PowerShell concepts and uses 

Windows PowerShell is a task automation and configuration management framework released by Microsoft, including a command line shell and a scripting language environment. It is built on the .NET Framework and accepts and returns .NET objects.

Uses include:

1. System management: PowerShell scripts can be used to automate daily system management and configuration tasks.

2. Network management: For example, you can use PowerShell scripts to manage network settings, including network adapter settings, IP address configuration, etc.

3. File operations: PowerShell scripts can be used to automate file operations, such as copying files, deleting files, renaming files, etc.

4. Data processing: PowerShell can process various data such as text, XML, CSV, etc., and has a wealth of data processing commands.

5. System monitoring: PowerShell scripts can be used to monitor the running status of the system, such as CPU usage, memory usage, hard disk usage, etc.

6. Software development and testing: PowerShell is powerful and suitable for software development and testing. For example, PowerShell can be used to automate compilation, testing, packaging, deployment , etc.

7. Server management: PowerShell provides a wealth of commands to manage various functions of Windows Server, including AD (Active Directory), IIS, Exchange Server, SQL Server, etc.

Why use PowerShell to install Boost library on Windows? 

Developing a Boost program requires configuring the locations of the Boost header files and Boost link libraries. The Windows management program's compilation, packaging, and deployment tool is PowerShell.

Step 1: Open the PowerShell window

Open a cmd window and enter the powershell command.

Step 2: Switch to the Boost decompression directory and execute the following command.

Windows PowerShell
版权所有(C) Microsoft Corporation。保留所有权利。

安装最新的 PowerShell,了解新功能和改进!https://aka.ms/PSWindows

PS C:\Users\zzg> cd D:\Boost\boost_1_83_0
PS D:\Boost\boost_1_83_0> .\bootstrap.bat
Building Boost.Build engine
LOCALAPPDATA=C:\Users\zzg\AppData\Local
Found with vswhere C:\Program Files\Microsoft Visual Studio\2022\Community
Found with vswhere C:\Program Files\Microsoft Visual Studio\2022\Community
Call_If_Exists "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\..\..\VC\Auxiliary\Build\vcvarsall.bat"  AMD64
**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.5.5
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
###
### Using 'vc143' toolset.
###

Step 3: .\bootstrap.bat· After the operation is completed, the result is as shown in the figure below. Several more files will be used for library construction and compilation:

 Expansion: .\b2 --help Learn what parameters can be configured

PS D:\Boost\boost_1_83_0> .\b2 --help
B2 4.10-git

Project-specific help:

  Project has jamfile at Jamroot

Usage:

  b2 [options] [properties] [install|stage]

  Builds and installs Boost.

Targets and Related Options:

  install                 Install headers and compiled library files to the
  =======                 configured locations (below).

  --prefix=<PREFIX>       Install architecture independent files here.
                          Default: C:\Boost on Windows
                          Default: /usr/local on Unix, Linux, etc.

  --exec-prefix=<EPREFIX> Install architecture dependent files here.
                          Default: <PREFIX>

  --libdir=<LIBDIR>       Install library files here.
                          Default: <EPREFIX>/lib

  --includedir=<HDRDIR>   Install header files here.
                          Default: <PREFIX>/include

  --cmakedir=<CMAKEDIR>   Install CMake configuration files here.
                          Default: <LIBDIR>/cmake

  --no-cmake-config       Do not install CMake configuration files.

  stage                   Build and install only compiled library files to the
  =====                   stage directory.

  --stagedir=<STAGEDIR>   Install library files here
                          Default: ./stage

Other Options:

  --build-type=<type>     Build the specified pre-defined set of variations of
                          the libraries. Note, that which variants get built
                          depends on what each library supports.

                              -- minimal -- (default) Builds a minimal set of
                              variants. On Windows, these are static
                              multithreaded libraries in debug and release
                              modes, using shared runtime. On Linux, these are
                              static and shared multithreaded libraries in
                              release mode.

                              -- complete -- Build all possible variations.

  --build-dir=DIR         Build in this location instead of building within
                          the distribution tree. Recommended!

  --show-libraries        Display the list of Boost libraries that require
                          build and installation steps, and then exit.

  --layout=<layout>       Determine whether to choose library names and header
                          locations such that multiple versions of Boost or
                          multiple compilers can be used on the same system.

                              -- versioned -- Names of boost binaries include
                              the Boost version number, name and version of
                              the compiler and encoded build properties. Boost
                              headers are installed in a subdirectory of
                              <HDRDIR> whose name contains the Boost version
                              number.

                              -- tagged -- Names of boost binaries include the
                              encoded build properties such as variant and
                              threading, but do not including compiler name
                              and version, or Boost version. This option is
                              useful if you build several variants of Boost,
                              using the same compiler.

                              -- system -- Binaries names do not include the
                              Boost version number or the name and version
                              number of the compiler. Boost headers are
                              installed directly into <HDRDIR>. This option is
                              intended for system integrators building
                              distribution packages.

                          The default value is 'versioned' on Windows, and
                          'system' on Unix.

  --buildid=ID            Add the specified ID to the name of built libraries.
                          The default is to not add anything.

  --python-buildid=ID     Add the specified ID to the name of built libraries
                          that depend on Python. The default is to not add
                          anything. This ID is added in addition to --buildid.

  --help                  This message.

  --with-<library>        Build and install the specified <library>. If this
                          option is used, only libraries specified using this
                          option will be built.

  --without-<library>     Do not build, stage, or install the specified
                          <library>. By default, all libraries are built.

Properties:

  toolset=toolset         Indicate the toolset to build with.

  variant=debug|release   Select the build variant

  link=static|shared      Whether to build static or shared libraries

  threading=single|multi  Whether to build single or multithreaded binaries

  runtime-link=static|shared
                          Whether to link to static or shared C and C++
                          runtime.


General command line usage:

    b2 [options] [properties] [targets]

  Options, properties and targets can be specified in any order.

Important Options:

  * --clean Remove targets instead of building
  * -a Rebuild everything
  * -n Don't execute the commands, only print them
  * -d+2 Show commands as they are executed
  * -d0 Suppress all informational messages
  * -q Stop at first error
  * --reconfigure Rerun all configuration checks
  * --durations[=N] Report top N targets by execution time
  * --debug-configuration Diagnose configuration
  * --debug-building Report which targets are built with what properties
  * --debug-generator Diagnose generator search/execution

Further Help:

  The following options can be used to obtain additional documentation.

  * --help-options Print more obscure command line options.
  * --help-internal B2 implementation details.
  * --help-doc-options Implementation details doc formatting.

...found 1 target...

Step 4: According to the functional requirements, enter the installation instructions, configure the corresponding parameters, and wait for the installation to be completed.

Example: I do not need python, wave and other libraries, and store the compiled files in the VS2022 folder.

 .\b2 stage --without-python --without-mpi --without-wave --stagedir="D:\Boost\boost_1_83_0\VS2022"

Press Enter and wait for the installation to complete. 

PS D:\Boost\boost_1_83_0> .\b2 stage --without-python --without-mpi --without-wave --stagedir="D:\Boost\boost_1_83_0\VS2
022"
Performing configuration checks

    - default address-model    : 64-bit [1]
    - default architecture     : x86 [1]
    - compiler supports SSE2   : yes [2]
    - compiler supports SSE4.1 : yes [2]
    - has synchronization.lib  : yes [2]
    - has std::atomic_ref      : no [2]
    - has statx                : no [2]
    - has statx syscall        : no [2]
    - has BCrypt API           : yes [2]
    - has init_priority attribute : no [2]
    - has stat::st_blksize     : no [2]
    - has stat::st_mtim        : no [2]
    - has stat::st_mtimensec   : no [2]
    - has stat::st_mtimespec   : no [2]
    - has stat::st_birthtim    : no [2]
    - has stat::st_birthtimensec : no [2]
    - has stat::st_birthtimespec : no [2]
    - has fdopendir(O_NOFOLLOW) : no [2]
    - has dirent::d_type       : no [2]
    - has POSIX *at APIs       : no [2]
    - cxx11_auto_declarations  : yes [2]
    - cxx11_constexpr          : yes [2]
    - cxx11_defaulted_functions : yes [2]
    - cxx11_final              : yes [2]
    - cxx11_hdr_mutex          : yes [2]
    - cxx11_hdr_tuple          : yes [2]
    - cxx11_lambdas            : yes [2]
    - cxx11_noexcept           : yes [2]
    - cxx11_nullptr            : yes [2]
    - cxx11_rvalue_references  : yes [2]
    - cxx11_template_aliases   : yes [2]
    - cxx11_thread_local       : yes [2]
    - cxx11_variadic_templates : yes [2]
    - has_icu builds           : no [2]
******

Visual Studio 2022 integrated Boost quick start

Step 1: Create an empty project

 

Step 2: Configure project properties 

The include directory  and library directory need to be configured in the project configuration.   

 

Secondly, the configuration and library directory  are shown in the figure below: 

 

 

Quick Start with Boost Library 

smart pointer

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

using namespace boost;
using namespace std;

class MyClass {
public:
    MyClass() {
        cout << "MyClass constructor"; }
    ~MyClass() {
         cout << "MyClass destructor"; }
};

int main() {
    // 声明智能指针
    scoped_ptr<MyClass> ptr(new MyClass);

    // 现在我们可以像使用常规指针一样使用 scoped_ptr
   // ...

   // 当 ptr 超出作用域时,MyClass 对象将被删除
    return 0;
}

Warm reminder: The basic function of scoped_ptr: automatically release the resources it manages.

Knowledge expansion: In the Boost library, smart pointers are a very useful resource management tool.

Smart pointers are "smart" in that they automatically manage allocated objects and automatically release the object when it is no longer needed . This automatic management feature can help avoid memory leaks and eliminate the trouble of manually freeing memory .

Smart pointers in the Boost library are divided into the following categories:

1. boost::scoped_ptr: This is a simple smart pointer that guarantees that the object will be deleted when its scope ends. It does not support the sharing of pointers, nor can it be put into the container class of the C++ standard library.

2. boost::shared_ptr: This is a reference-counted smart pointer that supports copy operations and shared object ownership with other shared_ptr. When the last referenced shared_ptr is destroyed or released, the object pointed to will be deleted.

3. boost::weak_ptr: This is a smart pointer that assists shared_ptr. It observes shared_ptr but does not increase its reference count. Mainly used to solve the circular reference problem caused by shared_ptr.

4. boost::unique_ptr: This is a smart pointer added in the C++11 standard, which represents the semantics of exclusive ownership.

5. boost::intrusive_ptr: For those cases where the reference count is embedded in the user object, using this smart pointer can reduce memory overhead.

function object 

What is a function object?

In C++, function objects (also called functors) are objects that behave like functions. They are a way to simulate the functionality of a function through an instance of a class.

Advantages: Compared with ordinary functions, it can contain local state information.

Boost for function object expansion

Function objects in the Boost library include some common function objects (such as boost::bind, used to bind functions or function objects to their parameters), as well as extensions and supplements to function objects in STL. For example, the Boost.Function library provides function wrappers that can store any callable target (that is, an object that can be called with "()"), including functions, function pointers, and function objects.

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

using namespace std;
void print_num(int x) {
	cout << "int is:" << x <<endl;
}

int main() {
	boost::function<void(int)> f = print_num;
	f(5);
	return 0;
}

event handling

Event handling involves creating and managing an event loop, listening for input or triggering events, and taking appropriate actions when events occur.

The main tool in the Boost library is Boost.Asio, which you can use to write asynchronous IO operations (such as network or timer operations). Boost.Asio supports multi-threading and concurrent connections, as well as wait/notify including timeouts, cancellation and sigaction actions.

Here is a basic example of Boost.Asio showing how to use it to create a timer:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(const boost::system::error_code& /*e*/)
{
	std::cout << "Hello, world!" << std::endl;
}

int main()
{
	boost::asio::io_service io;
	boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));
	timer.async_wait(&print);
	io.run();

	return 0;
}

Note: First create an io_service and a timer. Then we set the timer to fire after 5 seconds and register a callable object (in this case the print function) to act as an event handler. Then we start the event loop of io_service. When the timer expires, the print function will be called and output "Hello, world!".

You can use Boost.Asio to implement more complex event processing operations, including Socket programming, serial port operations, signal processing, and Coroutines, Futures, Threads, and more.

String processing

The Boost C++ library provides powerful support for string operations, including ordinary string processing, formatted strings using variable parameter templates, regular expression matching and replacement, and UNICODE string conversion.
 

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/locale.hpp>
#include <iostream>

using namespace std;


int main() {
	string str = " hello, world! ";
	cout << "str is:" << str << endl;
	// 字符串大写转换
	boost::to_upper(str);
	cout << "str is:" << str << endl;

	// 字符串格式化
	cout << boost::format("%1% %2% %3%") % 1 % 2 % 3;

	// 字符串正则表达式
	string s = "Boost Libraries";
	boost::regex expr{ "\\w+\\s\\w+" };
	cout << std::boolalpha << boost::regex_match(s, expr) << '\n';

	// 类型转换
	int x = boost::lexical_cast<int>("123");
	string s1 = boost::lexical_cast<string>(123);

	cout << "x is:" << x << endl;
	cout << "s1 is:" << s1 << endl;

	// unicode 编码
	std::locale loc = boost::locale::generator().generate("");

	std::string original = "é";
	std::cout << "Size: " << original.size() << std::endl;

	std::string normalized = boost::locale::normalize(original, boost::locale::norm_nfc, loc);
	std::cout << "Normalized Size: " << normalized.size() << std::endl;
	return 0;
}

1. Boost.StringAlgo library: The Boost.StringAlgo library is a string algorithm library that provides very powerful string processing functions, including search, comparison, conversion, trimming of spaces, splitting, merging and other operations. For example, you can use the trim function to remove spaces at the beginning and end of a string, and the split function can cut strings very conveniently.

```cpp
std::string str=" hello, world! ";
boost::trim(str);
```

2. Boost.Format library: The Boost.Format library provides a character with parameters similar to printf String formatting function. Compared with printf's writing method, Boost.Format's writing method is more intuitive and type-safe.

```cpp
std::cout << boost::format("%1% %2% %3%") %1 %2 %3; ``
`

3. Boost.Regex library: Boost.Regex library provides Regular expression support allows you to perform complex string matching and replacement operations. For example, you can easily use regular expressions to determine whether a string is an email address, or to extract all URLs from a text, etc.

```cpp
boost::regex reg("(http|https)://[^/]*");
```

4. Boost.Lexical_Cast library: The Boost.Lexical_Cast library can convert strings to other types, Or convert other types to strings. It supports all standard C++ types, and type conversions are type-safe.

```cpp
int x = boost::lexical_cast<int>("123");
std::string s = boost::lexical_cast<std::string>(123);
````

5. Boost.String library: Boost.String library It is a library for operating on std::string. It provides functions including splitting, removing spaces, replacing, searching, etc.

```cpp
std::string s = "Hello, World!";
boost::to_upper(s);
```

6. Boost.Unicode library: The Boost.Unicode library provides operations on UNICODE strings, including characters String conversion, case conversion, comparison and search, etc.

```cpp
boost::locale::generator gen;
std::locale loc=gen("en_US.UTF-8");
std::locale::global(loc);
```

Multithreading

Boost is a collection of portable and high-quality libraries for C++. Boost provides a series of libraries for multi-threaded programming, including boost.thread, boost.asio, etc.

1. Boost.Thread: Provides a general framework for multi-threaded programming, allowing developers to create and control threads, mutexes, condition variables, etc.

2. Boost.Asio: Used for network and low-level I/O programming, for example, developers can use it to create multi-threaded servers or clients.

The multi-threading library in Boost mainly focuses on providing low-level thread processing functions, such as thread creation, synchronization, mutual exclusion, etc. Compared with the multi-threading features supported by the programming language itself, Boost's multi-threading library provides more detailed control and can help developers better build complex multi-threaded applications.

Using Boost for multi-threaded programming can greatly simplify the code and improve the stability and portability of the code. But it also requires developers to have a certain familiarity and understanding of the principles and usage of multi-threading, otherwise it may cause some problems that are difficult to troubleshoot, such as deadlocks, resource preemption, etc.

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

void workerFunc()
{
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    std::cout << "Worker thread is executing." << std::endl;
}

int main(int argc, char* argv[])
{
    std::cout << "Main thread is running." << std::endl;

    // 创建并运行新的工作线程
    boost::thread workerThread(workerFunc);

    // 等待工作线程完成
    workerThread.join();

    std::cout << "Main thread is done." << std::endl;

    return 0;
}

Note: The program has a main thread and a working thread. When running, the working thread will print the output after a delay of one second, and then after it is completed, the main thread will print the completion information.

Guess you like

Origin blog.csdn.net/zhouzhiwengang/article/details/132824524