如何让B2构建器默认启用-jN并行编译Boost,支持动态获取核心数?
Absolutely, you can configure B2 to run parallel builds automatically—no need to type -j4 every time. Even better, you can set it to dynamically use all available cores instead of hardcoding a number. Here are the most straightforward methods:
1. Use Environment Variables (Simplest Approach)
B2 checks for the B2_JOBS or JOBS environment variables to determine default parallel jobs. You can set this dynamically in your shell configuration:
For Linux/WSL: Add this line to your
~/.bashrcor~/.profilefile:export B2_JOBS=$(nproc)nprocoutputs the number of available CPU cores automatically.For macOS: Use
sysctlinstead ofnproc:export B2_JOBS=$(sysctl -n hw.ncpu)
After reloading your shell (or running source ~/.bashrc), typing ./b2 will automatically use all your cores for parallel builds.
2. Configure via B2's Jam Configuration Files
If you prefer setting this directly in B2's config (instead of shell env vars), you can modify user-config.jam or create a site-config.jam file:
- Locate your
user-config.jam(usually in~/.user-config.jamor Boost'stools/build/srcdirectory, depending on your setup). - Add these lines to the file:
# Dynamically get core count and set default jobs import os ; local core_count = [ os.command-output nproc ] ; # Use "sysctl -n hw.ncpu" for macOS set-option jobs : $(core_count) ;
This uses B2's native Jam language to run nproc (or the macOS equivalent) and set the default jobs option to the result.
3. Create a Wrapper Script (Flexible Alternative)
If you want a portable way that doesn't rely on shell configs or Jam files, make a simple wrapper script:
- Create a file named
b2-auto(or whatever you prefer) in your Boost directory:#!/bin/bash # Auto-use all cores for B2 builds CORE_COUNT=$(nproc) # Replace with "sysctl -n hw.ncpu" on macOS ./b2 -j$CORE_COUNT "$@" - Make it executable:
chmod +x b2-auto
Now run ./b2-auto instead of ./b2—it'll use all cores and still pass through any other arguments you add (like install or variant=release).
Important Note
If you ever manually specify -jN (e.g., ./b2 -j2), that value will override your default setting—so you can still force a specific number of jobs when needed.
内容的提问来源于stack exchange,提问作者einpoklum

