Windows 11にBoostライブラリをインストールする

ライブラリのダウンロードとインストールを強化する

Boost 公式 Web サイトのアドレス: https://www.boost.org/  、まず公式 Web サイトにアクセスして、対応するバージョンの Boost ライブラリ ファイルをダウンロードします。以下に示す緑色のボックス内の[ダウンロード]をクリックして 、ダウンロード ページに入ります。 

ダウンロード ページにアクセスし、必要なバージョンをダウンロードします。現在ダウンロードしているバージョンは 1.83.0、Windows バージョンは boost_1_83_0.7z です。 

 

ライブラリのインストールを強化する 

ダウンロードしたファイル パッケージを解凍すると、次の図のようになります。

知識の拡充: Windows PowerShell の概念と使用法 

Windows PowerShell は、Microsoft によってリリースされたタスク自動化および構成管理フレームワークであり、コマンド ライン シェルとスクリプト言語環境が含まれています。これは .NET Framework 上に構築されており、.NET オブジェクトを受け入れて返します。

用途は次のとおりです。

1. システム管理: PowerShell スクリプトを使用して、日常のシステム管理および構成タスクを自動化できます。

2. ネットワーク管理: たとえば、PowerShell スクリプトを使用して、ネットワーク アダプター設定、IP アドレス構成などのネットワーク設定を管理できます。

3. ファイル操作: PowerShell スクリプトを使用して、ファイルのコピー、ファイルの削除、ファイル名の変更などのファイル操作を自動化できます。

4. データ処理:PowerShell はテキスト、XML、CSV などのさまざまなデータを処理でき、豊富なデータ処理コマンドを備えています。

5. システム監視: PowerShell スクリプトを使用して、CPU 使用率、メモリ使用率、ハードディスク使用率などのシステムの実行ステータスを監視できます。

6. ソフトウェア開発とテスト: PowerShell は強力で、ソフトウェア開発とテストに適しています。たとえば、PowerShell を使用して、コンパイル、テスト、パッケージ化、展開などを自動化できます。

7. サーバー管理: PowerShell は、AD (Active Directory)、IIS、Exchange Server、SQL Server など、Windows Server のさまざまな機能を管理するための豊富なコマンドを提供します。

Windows に Boost ライブラリをインストールするのに PowerShell を使用するのはなぜですか? 

Boost プログラムの開発には、Boost ヘッダー ファイルと Boost リンク ライブラリの場所を構成する必要があります。Windows 管理プログラムのコンパイル、パッケージ化、展開ツールは PowerShell です。

ステップ 1: PowerShell ウィンドウを開く

cmd ウィンドウを開き、powershell コマンドを入力します。

ステップ 2: Boost 解凍ディレクトリに切り替えて、次のコマンドを実行します。

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.
###

ステップ 3: .\bootstrap.bat · 操作が完了すると、結果は次の図のようになります。さらにいくつかのファイルがライブラリの構築とコンパイルに使用されます。

 拡張:.\b2 --help どのようなパラメータを構成できるかを学びます

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...

ステップ 4: 機能要件に従って、インストール手順を入力し、対応するパラメータを設定し、インストールが完了するまで待ちます。

例: Python、wave、その他のライブラリは必要なく、コンパイルされたファイルを VS2022 フォルダーに保存します。

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

Enter キーを押して、インストールが完了するまで待ちます。 

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 統合 Boost クイック スタート

ステップ 1: 空のプロジェクトを作成する

 

ステップ 2: プロジェクトのプロパティを構成する 

インクルード ディレクトリ ライブラリ ディレクトリはプロジェクト構成で構成する必要があります。   

 

次に、構成ディレクトリとライブラリ ディレクトリ を次の図に示します。 

 

 

Boost ライブラリを使用したクイック スタート 

スマートポインター

#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;
}

注意:scoped_ptr の基本機能: 管理しているリソースを自動的に解放します。

知識の拡張: Boost ライブラリでは、スマート ポインターは非常に便利なリソース管理ツールです。

スマート ポインタは、割り当てられたオブジェクトを自動的に管理し、不要になったオブジェクトを自動的に解放するという点で「スマート」ですこの自動管理機能は、メモリ リークを回避し手動でメモリを解放する手間を省くのに役立ちます

Boost ライブラリのスマート ポインターは、次のカテゴリに分類されます。

1. boost::scoped_ptr: これは、スコープが終了したときにオブジェクトが削除されることを保証する単純なスマート ポインターです。ポインターの共有はサポートされておらず、C++ 標準ライブラリのコンテナー クラスに含めることもできません。

2. boost::shared_ptr: これは、コピー操作と他のshared_ptrとの共有オブジェクト所有権をサポートする、参照カウントされるスマート ポインタです。最後に参照されたshared_ptrが破棄または解放されると、ポイントされたオブジェクトは削除されます。

3. boost::weak_ptr: これは、shared_ptr を支援するスマート ポインタであり、shared_ptr を監視しますが、その参照カウントは増加しません。主に、shared_ptr によって引き起こされる循環参照の問題を解決するために使用されます。

4. boost::unique_ptr: これは、C++11 標準で追加されたスマート ポインターであり、排他的所有権のセマンティクスを表します。

5. boost::intrusive_ptr: 参照カウントがユーザー オブジェクトに埋め込まれている場合、このスマート ポインターを使用するとメモリ オーバーヘッドを削減できます。

関数オブジェクト 

関数オブジェクトとは何ですか?

C++ では、関数オブジェクト (ファンクターとも呼ばれます) は、関数のように動作するオブジェクトです。これらは、クラスのインスタンスを通じて関数の機能をシミュレートする方法です。

利点: 通常の関数と比較して、ローカルな状態情報を含めることができます。

関数オブジェクト拡張のブースト

Boost ライブラリの関数オブジェクトには、いくつかの一般的な関数オブジェクト (関数または関数オブジェクトをパラメータにバインドするために使用される boost::bind など) に加え、STL の関数オブジェクトの拡張機能や補足機能が含まれます。たとえば、Boost.Function ライブラリは、関数、関数ポインター、関数オブジェクトなど、呼び出し可能なターゲット (つまり、「()」で呼び出すことができるオブジェクト) を格納できる関数ラッパーを提供します。

#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;
}

イベント処理

イベント処理には、イベント ループの作成と管理、入力のリッスンまたはイベントのトリガー、イベント発生時の適切なアクションの実行が含まれます。

Boost ライブラリの主なツールは Boost.Asio で、これを使用して非同期 IO 操作 (ネットワーク操作やタイマー操作など) を作成できます。Boost.Asio は、マルチスレッドと同時接続に加え、タイムアウト、キャンセル、sigaction アクションを含む待機/通知をサポートします。

以下は、Boost.Asio を使用してタイマーを作成する方法を示す基本的な例です。

#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;
}

注: まず、io_service とタイマーを作成します。次に、5 秒後にタイマーが起動するように設定し、イベント ハンドラーとして機能する呼び出し可能オブジェクト (この場合は print 関数) を登録します。次に、io_service のイベント ループを開始し、タイマーが切れると print 関数が呼び出され、「Hello, world!」が出力されます。

Boost.Asio を使用すると、ソケット プログラミング、シリアル ポート操作、信号処理、コルーチン、フューチャー、スレッドなどを含む、より複雑なイベント処理操作を実装できます。

文字列処理

Boost C++ ライブラリは、通常の文字列処理、可変パラメータ テンプレートを使用した書式設定された文字列、正規表現の一致と置換、UNICODE 文字列変換などの文字列操作の強力なサポートを提供します。
 

#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 ライブラリ: Boost.StringAlgo ライブラリは、検索、比較、変換、スペースのトリミング、分割、結合、その他の操作を含む、非常に強力な文字列処理機能を提供する文字列アルゴリズム ライブラリです。たとえば、trim 関数を使用すると文字列の先頭と末尾のスペースを削除したり、split 関数を使用すると文字列を非常に便利に切り取ることができます。

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

2. Boost.Format ライブラリ: Boost.Format ライブラリは、printf String 書式設定に似たパラメータを持つ文字を提供します。関数。printf の記述方法と比較して、Boost.Format の記述方法はより直感的でタイプセーフです。

```cpp
std::cout << boost::format("%1% %2% %3%") %1 %2 %3; `` ` 3. Boost.Regex
ライブラリ

: Boost.Regex ライブラリは通常の式のサポートにより、複雑な文字列の一致および置換操作を実行できます。たとえば、正規表現を使用して、文字列が電子メール アドレスであるかどうかを判断したり、テキストからすべての URL を抽出したりすることが簡単にできます。

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

Boost.Lexical_Cast ライブラリ: Boost.Lexical_Cast ライブラリは文字列を他の型に変換できます。他の型を文字列に変換します。すべての標準 C++ 型をサポートし、型変換はタイプセーフです。

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

5. Boost.String ライブラリ: Boost.String library std::string を操作するためのライブラリで、分割、スペース削除、置換、検索等の機能を提供します。

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

6. Boost.Unicode ライブラリ: Boost.Unicode ライブラリは、文字列変換を含む UNICODE 文字列に対する操作を提供します。 、大文字と小文字の変換、比較および検索など。

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

マルチスレッド化

Boost は、移植性の高い高品質な C++ ライブラリのコレクションです。Boost は、boost.thread、boost.asio など、マルチスレッド プログラミング用の一連のライブラリを提供します。

1. Boost.Thread: マルチスレッド プログラミングのための一般的なフレームワークを提供し、開発者がスレッド、ミューテックス、条件変数などを作成および制御できるようにします。

2. Boost.Asio: ネットワークおよび低レベル I/O プログラミングに使用されます。たとえば、開発者はこれを使用してマルチスレッド サーバーまたはクライアントを作成できます。

Boost のマルチスレッド ライブラリは、主に、スレッドの作成、同期、相互排他などの低レベルのスレッド処理機能を提供することに重点を置いています。プログラミング言語自体でサポートされているマルチスレッド機能と比較して、Boost のマルチスレッド ライブラリはより詳細な制御を提供し、開発者が複雑なマルチスレッド アプリケーションをより適切に構築できるように支援します。

マルチスレッド プログラミングに Boost を使用すると、コードが大幅に簡素化され、コードの安定性と移植性が向上します。ただし、開発者はマルチスレッドの原理と使用法についてある程度の知識と理解を持っている必要もあります。そうしないと、デッドロックやリソースのプリエンプションなど、トラブルシューティングが困難な問題が発生する可能性があります。

#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;
}

注: プログラムにはメイン スレッドと作業スレッドがあります。実行中、作業スレッドは 1 秒の遅延後に出力を出力し、完了後にメイン スレッドは完了情報を出力します。

おすすめ

転載: blog.csdn.net/zhouzhiwengang/article/details/132824524