[[b2.overview]]
= Overview

This section will provide the information necessary to create your own
projects using B2. The information provided here is relatively
high-level, and the link:#b2.reference[Reference] as well as the on-line
help system must be used to obtain low-level documentation (see
link:#b2.overview.invocation.options.help[`--help`]).

B2 has two parts — a build engine with its own interpreted
language, and B2 itself, implemented in that language. The
chain of events when you type `b2` on the command line is as follows:

1.  The B2 executable tries to find B2 modules and
loads the top-level module. The exact process is described in
link:#b2.reference.init[the section called “Initialization”]
2.  The top-level module loads user-defined configuration files,
`user-config.jam` and `site-config.jam`, which define available
toolsets.
3.  The Jamfile in the current directory is read. That in turn might
cause reading of further Jamfiles. As a result, a tree of projects is
created, with targets inside projects.
4.  Finally, using the build request specified on the command line,
B2 decides which targets should be built and how. That
information is passed back to Boost.Jam, which takes care of actually
running the scheduled build action commands.

So, to be able to successfully use B2, you need to know only
four things:

* link:#b2.overview.configuration[How to configure B2]
* link:#b2.overview.targets[How to declare targets in Jamfiles]
* link:#b2.overview.build_process[How the build process works]
* Some Basics about the Boost.Jam language. See
link:#b2.overview.jam_language[the section called “Boost.Jam Language”].

[[b2.overview.concepts]]
== Concepts

B2 has a few unique concepts that are introduced in this
section. The best way to explain the concepts is by comparison with more
classical build tools.

When using any flavor of make, you directly specify _targets_ and
commands that are used to create them from other target. The below
example creates `a.o` from `a.c` using a hardcoded compiler invocation
command.

[source,make]
----
a.o: a.c
    g++ -o a.o -g a.c
----

This is a rather low-level description mechanism and it's hard to adjust
commands, options, and sets of created targets depending on the compiler
and operating system used.

To improve portability, most modern build system provide a set of
higher-level functions that can be used in build description files.
Consider this example:

[source,cmake]
----
add_program ("a", "a.c")
----

This is a function call that creates the targets necessary to create an
executable file from the source file `a.c`. Depending on configured
properties, different command lines may be used. However, `add_program`
is higher-level, but rather thin level. All targets are created
immediately when the build description is parsed, which makes it
impossible to perform multi-variant builds. Often, change in any build
property requires a complete reconfiguration of the build tree.

In order to support true multi-variant builds, B2 introduces the
concept of a metatarget definition main target metatarget
_metatarget_ -- an object that is created when the build description is
parsed and can be called later with specific build properties to
generate actual targets.

Consider an example:

[source]
----
exe a : a.cpp ;
----

When this declaration is parsed, B2 creates a metatarget, but
does not yet decide what files must be created, or what commands must be
used. After all build files are parsed, B2 considers the
properties requested on the command line. Supposed you have invoked
B2 with:

[source,shell]
----
b2 toolset=gcc toolset=msvc
----

In that case, the metatarget will be called twice, once with
`toolset=gcc` and once with `toolset=msvc`. Both invocations will
produce concrete targets, that will have different extensions and use
different command lines.

Another key concept is _build property_. A build
property is a variable that affects the build process. It can be
specified on the command line, and is passed when calling a metatarget.
While all build tools have a similar mechanism, B2 differs by
requiring that all build properties are declared in advance, and
providing a large set of properties with portable semantics.

The final concept is _property propagation_.
B2 does not require that every metatarget is called with the
same properties. Instead, the "top-level" metatargets are called with
the properties specified on the command line. Each metatarget can elect
to augment or override some properties (in particular, using the
requirements mechanism, see
link:#b2.overview.targets.requirements[the section called “Requirements”]).
Then, the dependency metatargets are called with the modified properties and
produce concrete targets that are then used in the build process. Of
course, dependency metatargets maybe in turn modify build properties and
have dependencies of their own.

For a more in-depth treatment of the requirements and concepts, you may
refer to http://syrcose.ispras.ru/2009/files/04_paper.pdf[SYRCoSE 2009
B2 article].

[[b2.overview.jam_language]]
== Boost.Jam Language

This section will describe the basics of the Boost.Jam language—just
enough for writing Jamfiles. For more information, please see the
link:#b2.jam[Boost.Jam] documentation.

link:#b2.jam[Boost.Jam] has an interpreted, procedural language. On
the lowest level, a link:#b2.jam[Boost.Jam] program consists of
variables and _rules_ (the Jam term for functions). They are grouped
into modules—there is one global module and a number of named modules.
Besides that, a link:#b2.jam[Boost.Jam] program contains classes and
class instances.

Syntactically, a link:#b2.jam[Boost.Jam] program consists of two kinds
of elements—keywords (which have a special meaning to
link:#b2.jam[Boost.Jam]) and literals. Consider this code:

[source]
----
a = b ;
----

which assigns the value `b` to the variable `a`. Here, `=` and `;` are
keywords, while `a` and `b` are literals.

WARNING: All syntax elements, even keywords, must be separated by spaces. For
example, omitting the space character before `;` will lead to a syntax
error.

If you want to use a literal value that is the same as some keyword, the
value can be quoted:

[source]
----
a = "=" ;
----

All variables in link:#b2.jam[Boost.Jam] have the same type—list of
strings. To define a variable one assigns a value to it, like in the
previous example. An undefined variable is the same as a variable with
an empty value. Variables can be accessed using the `$(variable)`
syntax. For example:

[source]
----
a = $(b) $(c) ;
----

Rules are defined by specifying the rule name, the parameter names, and
the allowed value list size for each parameter.

[source]
----
rule example
 (
     parameter1 :
     parameter2 ? :
     parameter3 + :
     parameter4 *
 )
 {
    # rule body
 }
----

When this rule is called, the list passed as the first argument must
have exactly one value. The list passed as the second argument can
either have one value of be empty. The two remaining arguments can be
arbitrarily long, but the third argument may not be empty.

The overview of link:#b2.jam[Boost.Jam] language statements is given
below:

[source]
----
helper 1 : 2 : 3 ;
x = [ helper 1 : 2 : 3 ] ;
----

This code calls the named rule with the specified arguments. When the
result of the call must be used inside some expression, you need to add
brackets around the call, like shown on the second line.

[source]
----
if cond { statements } [ else { statements } ]
----

This is a regular if-statement. The condition is composed of:

* Literals (true if at least one string is not empty)
* Comparisons: `a operator b` where _operator_ is one of `=`, `!=`, `<`,
`>`, `<=` or `>=`. The comparison is done pairwise between each string
in the left and the right arguments.
* Logical operations: `! a`, `a && b`, `a || b`
* Grouping: `( cond )`

[source]
----
for var in list { statements }
----

Executes statements for each element in list, setting the variable `var`
to the element value.

[source]
----
while cond { statements }
----

Repeatedly execute statements while cond remains true upon entry.

[source]
----
return values ;
----

This statement should be used only inside a rule and returns `values` to
the caller of the rule.

[source]
----
import module ;
import module : rule ;
----

The first form imports the specified module. All rules from that module
are made available using the qualified name: `module.rule`. The second form
imports the specified rules only, and they can be called using unqualified
names.

[[b2.overview.jam_language.actions]]
Sometimes, you need to specify the actual command lines to be used when
creating targets. In the jam language, you use named actions to do this.
For example:

[source]
----
actions create-file-from-another
{
    create-file-from-another $(<) $(>)
}
----

This specifies a named action called `create-file-from-another`. The text
inside braces is the command to invoke. The `$(<)` variable will be expanded
to a list of generated files, and the `$(>)` variable will be expanded to a
list of source files.

To adjust the command line flexibly, you can define a rule with the same
name as the action and taking three parameters -- targets, sources and
properties. For example:

[source]
----
rule create-file-from-another ( targets * : sources * : properties * )
{
   if <variant>debug in $(properties)
   {
       OPTIONS on $(targets) = --debug ;
   }
}
actions create-file-from-another
{
    create-file-from-another $(OPTIONS) $(<) $(>)
}
----

In this example, the rule checks if a certain build property is
specified. If so, it sets the variable `OPTIONS` that is then used
inside the action. Note that the variables set "on a target" will be
visible only inside actions building that target, not globally. Were
they set globally, using variable named `OPTIONS` in two unrelated
actions would be impossible.

More details can be found in the Jam reference,
link:#jam.language.rules[the section called “Rules”].

[[b2.overview.configuration]]
== Configuration

On startup, B2 searches and reads three configuration files:
`site-config.jam`, `user-config.jam`, and `project-config.jam`. The
first one is usually installed and maintained by a system administrator,
and the second is for the user to modify. You can edit the one in the
top-level directory of your B2 installation or create a copy in
your home directory and edit the copy. The third is used for project
specific configuration. The following table explains where the files are
searched.

.Search paths for configuration files
[cols="h,a,a,a"]
|===
| ^| site-config.jam ^| user-config.jam ^| project-config.jam

.^| Linux
|
`/etc`

`$HOME`

`$BOOST_BUILD_PATH`
|
`$HOME`

`$BOOST_BUILD_PATH`
|
`.`

`..`

`../..`

...

.^| Windows
|
`%SystemRoot%`

`%HOMEDRIVE%%HOMEPATH%`

`%HOME%`

`%BOOST_BUILD_PATH%`
|
`%HOMEDRIVE%%HOMEPATH%`

`%HOME%`

`%BOOST_BUILD_PATH%`
|
`.`

`..`

`../..`

...
|===

Any of these files may also be overridden
link:#b2.reference.init.options.config[on the command line].

NOTE: You can use the `--debug-configuration` option to find which
configuration files are actually loaded.

Usually, `user-config.jam` just defines the available compilers and
other tools (see link:#b2.recipes.site-config[the section called “Targets
in site-config.jam”] for more advanced usage). A tool is configured using
the following syntax:

[source]
----
using tool-name : ... ;
----

The `using` rule is given the name of tool, and will make that tool
available to B2. For example,

[source]
----
using gcc ;
----

will make the http://gcc.gnu.org[GCC] compiler available.

NOTE: You can put `using <tool> ;` with no other argument in a Jamfile
that needs the `tool`, provided that the `tool` supports this usage.
In all other cases, the `using` rule should be in a configuration file.
The general principle is that descriptions in Jamfile should be
maintained as portable while configuration files are system specific.

All the supported tools are documented in
link:#b2.reference.tools[the section called “Builtin tools”], including the
specific options they take. Some general notes that apply to most {CPP}
compilers are below.

For all the {CPP} compiler toolsets that B2 supports
out-of-the-box, the list of parameters to `using` is the same:
`toolset-name`, `version`, `invocation-command`, and `options`.

If you have a single compiler, and the compiler executable

* has its “usual name” and is in the `PATH`, or
* was installed in a standard “installation directory”, or
* can be found using a global system like the Windows registry.

it can be configured by simply:

[source]
----
using tool-name ;
----

If the compiler is installed in a custom directory, you should provide
the command that invokes the compiler, for example:

[source]
----
using gcc : : g++-3.2 ;
using msvc : : "Z:/Programs/Microsoft Visual Studio/vc98/bin/cl" ;
----

Some B2 toolsets will use that path to take additional actions
required before invoking the compiler, such as calling vendor-supplied
scripts to set up its required environment variables. When the compiler
executables for C and {CPP} are different, the path to the {CPP} compiler
executable must be specified. The command can be any command allowed by
the operating system. For example:

[source]
----
using msvc : : echo Compiling && foo/bar/baz/cl ;
----

will work.

To configure several versions of a toolset, simply invoke the `using`
rule multiple times:

[source]
----
using gcc : 3.3 ;
using gcc : 3.4 : g++-3.4 ;
using gcc : 3.2 : g++-3.2 ;
using gcc : 5 ;
using clang : 3.9 ;
using msvc : 14.0 ;
----

Note that in the first call to `using`, the compiler found in the `PATH`
will be used, and there is no need to explicitly specify the command.

Many of toolsets have an `options` parameter to fine-tune the
configuration. All of B2's standard compiler toolsets accept
four options `cflags`, `cxxflags`, `compileflags` and `linkflags` as
`options` specifying flags that will be always passed to the
corresponding tools. There must not be a space between the tag for the
option name and the value. Values of the `cflags` feature are passed
directly to the C compiler, values of the `cxxflags` feature are passed
directly to the {CPP} compiler, and values of the `compileflags` feature
are passed to both. For example, to configure a `gcc` toolset so that it
always generates 64-bit code you could write:

[source]
----
using gcc : 3.4 : : <compileflags>-m64 <linkflags>-m64 ;
----

If multiple of the same type of options are needed, they can be
concatenated with quotes or have multiple instances of the option tag.

[source]
----
using gcc : 5 : : <cxxflags>"-std=c++14 -O2" ;
using clang : 3.9 : : <cxxflags>-std=c++14 <cxxflags>-O2 ;
----

Multiple variations of the same tool can be used for most tools. These
are delineated by the version passed in. Because the dash '-' cannot be
used here, the convention has become to use the tilde '~' to delineate
variations.

[source]
----
using gcc : 5 : g++-5 : ; # default is C++ 98
using gcc : 5~c++03 : g++-5 : <cxxflags>-std=c++03 ; # C++ 03
using gcc : 5~gnu03 : g++-5 : <cxxflags>-std=gnu++03 ; # C++ 03 with GNU
using gcc : 5~c++11 : g++-5 : <cxxflags>-std=c++11 ; # C++ 11
using gcc : 5~c++14 : g++-5 : <cxxflags>-std=c++14 ; # C++ 14
----

These are then used as normal toolsets:

[source,shell]
----
b2 toolset=gcc-5 stage
b2 toolset=gcc-5~c++14 stage
----

WARNING: Although the syntax used to specify toolset options is very similar
to syntax used to specify requirements in Jamfiles, the toolset options are
not the same as features. Don't try to specify a feature value in
toolset initialization.

[[b2.overview.invocation]]
== Invocation

To invoke B2, type `b2` on the command line. Three kinds of
command-line tokens are accepted, in any order:

options::
  Options start with either one or two dashes. The standard options are
  listed below, and each project may add additional options
properties::
  Properties specify details of what you want to build (e.g. debug or
  release variant). Syntactically, all command line tokens with an equal
  sign in them are considered to specify properties. In the simplest
  form, a property looks like `feature=value`
target::
  All tokens that are neither options nor properties specify what
  targets to build. The available targets entirely depend on the project
  you are building.

[[b2.overview.invocation.examples]]
=== Examples

To build all targets defined in the Jamfile in the current directory
with the default properties, run:

[source,shell]
----
b2
----

To build specific targets, specify them on the command line:

[source,shell]
----
b2 lib1 subproject//lib2
----

To request a certain value for some property, add `property=value` to the
command line:

[source,shell]
----
b2 toolset=gcc variant=debug optimization=space
----

[[b2.overview.invocation.options]]
=== Options

B2 recognizes the following command line options.

[[b2.overview.invocation.options.help]]`--help`::
  Invokes the online help system. This prints general information on how
  to use the help system with additional --help* options.
`--clean`::
  Cleans all targets in the current directory and in any sub-projects.
  Note that unlike the `clean` target in make, you can use `--clean`
  together with target names to clean specific targets.
`--clean-all`::
  Cleans all targets, no matter where they are defined. In particular,
  it will clean targets in parent Jamfiles, and targets defined under
  other project roots.
`--build-dir`::
  Changes the build directories for all project roots being built. When
  this option is specified, all Jamroot files must declare a project
  name. The build directory for the project root will be computed by
  concatenating the value of the `--build-dir` option, the project name
  specified in Jamroot, and the build dir specified in Jamroot (or
  `bin`, if none is specified).
  The option is primarily useful when building from read-only media,
  when you can't modify Jamroot.
`--abbreviate-paths`::
  Compresses target paths by abbreviating each component. This option is
  useful to keep paths from becoming longer than the filesystem
  supports. See also link:#b2.reference.buildprocess.targetpath[the
  section called “Target Paths”].
`--hash`::
  Compresses target paths using an MD5 hash. This option is useful to
  keep paths from becoming longer than the filesystem supports. This
  option produces shorter paths than `--abbreviate-paths` does, but at the
  cost of making them less understandable. See also
  link:#b2.reference.buildprocess.targetpath[the section called “Target
  Paths”].
`--version`::
  Prints information on the B2 and Boost.Jam versions.
`-a`::
  Causes all files to be rebuilt.
`-n`::
  Do not execute the commands, only print them.
`-q`::
  Stop at the first error, as opposed to continuing to build targets
  that don't depend on the failed ones.
`-j N`::
  Run up to N commands in parallel. Default number of jobs is the number
  of detected available CPU threads. Note: There are circumstances when that
  default can be larger than the allocated cpu resources, for instance in some
  virtualized container installs.
`--config=filename`[[b2.reference.init.options.config]]::
  Override all link:#b2.overview.configuration[configuration files]
`--site-config=filename`::
  Override the default link:#b2.overview.configuration[site-config.jam]
`--user-config=filename`::
  Override the default link:#b2.overview.configuration[user-config.jam]
`--project-config=filename`::
  Override the default link:#b2.overview.configuration[project-config.jam]
`--debug-configuration`::
  Produces debug information about the loading of B2 and
  toolset files.
`--debug-building`::
  Prints what targets are being built and with what properties.
`--debug-generators`::
  Produces debug output from the generator search process. Useful for
  debugging custom generators.
`-d0`::
  Suppress all informational messages.
`-d N`::
  Enable cumulative debugging levels from 1 to n. Values are: +
  1.  Show the actions taken for building targets, as they are executed
  (the default).
  2.  Show "quiet" actions and display all action text, as they are
  executed.
  3.  Show dependency analysis, and target/source timestamps/paths.
  4.  Show arguments and timing of shell invocations.
  5.  Show rule invocations and variable expansions.
  6.  Show directory/header file/archive scans, and attempts at binding
  to targets.
  7.  Show variable settings.
  8.  Show variable fetches, variable expansions, and evaluation of
  '"if"' expressions.
  9.  Show variable manipulation, scanner tokens, and memory usage.
  10. Show profile information for rules, both timing and memory.
  11. Show parsing progress of Jamfiles.
  12. Show graph of target dependencies.
  13. Show change target status (fate).
`-d +N`::
  Enable debugging level `N`.
`-o file`::
  Write the updating actions to the specified file instead of running
  them.
`-s var=value`::
  Set the variable `var` to `value` in the global scope of the jam language
  interpreter, overriding variables imported from the environment.
`--command-database=_format_`::
  Output a compile commands database as _format_. Currently _format_ can be:
  `json`. (See xref:tasks#b2.tasks.commanddb[Command Database] for details.)
`--command-database-out=_file_`::
  Specify the _file_ path to output the commands database to.

[[b2.overview.invocation.properties]]
=== Properties

In the simplest case, the build is performed with a single set of
properties, that you specify on the command line with elements in the
form `feature=value`. The complete list of features can be found in
link:#b2.overview.builtins.features[the section called “Builtin features”].
The most common features are summarized below.

[cols=",,a",options="header"]
|===
|Feature |Allowed values |Notes

|variant
|debug,release
|

|link
|shared,static
|Determines if B2 creates shared or static libraries

|threading
|single,multi
|Cause the produced binaries to be thread-safe. This requires proper support
in the source code itself.

|address-model
|32,64
|Explicitly request either 32-bit or 64-bit code
generation. This typically requires that your compiler is appropriately
configured. Please refer to <<b2.reference.tools.compilers>> and your
compiler documentation in case of problems.

|toolset
|(Depends on configuration)
|The {CPP} compiler to use. See <<b2.reference.tools.compilers>> for a
detailed list.

|include
|(Arbitrary string)
|Additional include paths for C and {CPP} compilers.

|define
|(Arbitrary string)
|Additional macro definitions for C and {CPP} compilers. The string should be
either `SYMBOL` or `SYMBOL=VALUE`

|cxxflags
|(Arbitrary string)
|Custom options to pass to the {CPP} compiler.

|cflags
|(Arbitrary string)
|Custom options to pass to the C compiler.

|linkflags
|(Arbitrary string)
|Custom options to pass to the {CPP} linker.

|runtime-link
|shared,static
|Determines if shared or static version of C and {CPP} runtimes should be used.
|===

If you have more than one version of a given {CPP} toolset (e.g.
configured in `user-config.jam`, or autodetected, as happens with msvc),
you can request the specific version by passing `toolset-version` as the
value of the `toolset` feature, for example `toolset=msvc-8.0`.

If a feature has a fixed set of values it can be specified more than
once on the command line. In which case, everything will be built
several times -- once for each specified value of a feature. For
example, if you use

[source,shell]
----
b2 link=static link=shared threading=single threading=multi
----

Then a total of 4 builds will be performed. For convenience, instead of
specifying all requested values of a feature in separate command line
elements, you can separate the values with commas, for example:

[source,shell]
----
b2 link=static,shared threading=single,multi
----

The comma has this special meaning only if the feature has a fixed set
of values, so

[source,shell]
----
b2 include=static,shared
----

is not treated specially.

Multiple features may be grouped by using a forwards slash.

[source,shell]
----
b2 gcc/link=shared msvc/link=static,shared
----

This will build 3 different variants, altogether.

[[b2.overview.invocation.targets]]
=== Targets

All command line elements that are neither options nor properties are
the names of the targets to build. See link:#b2.reference.ids[the section
called “Target identifiers and references”]. If no target is specified, the
project in the current directory is built.

[[b2.overview.targets]]
== Declaring Targets

[[b2.overview.targets.main]]
A Main target is a user-defined named entity that can be built, for
example an executable file. Declaring a main target is usually done
using one of the main target rules described in
link:#b2.reference.rules[the section called “Builtin rules”]. The user can
also declare custom main target rules as shown in
link:#b2.extending.rules[the section called “Main target rules”].

anchor:b2.main-target-rule-syntax[]
Most main target rules in B2 have the same common signature:

[source]
----
rule rule-name (
     main-target-name :
     sources + :
     requirements * :
     default-build * :
     usage-requirements * )
----

* `main-target-name` is the name used to request the target on command
line and to use it from other main targets. A main target name may
contain alphanumeric characters, dashes (‘`-`’), and underscores
(‘`_`’).
* `sources` is the list of source files and other main targets that must
be combined.
* `requirements` is the list of properties that must always be present
when this main target is built.
* `default-build` is the list of properties that will be used unless
some other value of the same feature is already specified, e.g. on the
command line or by propagation from a dependent target.
* `usage-requirements` is the list of properties that will be propagated
to all main targets that use this one, i.e. to all its dependents.

Some main target rules have a different list of parameters as explicitly
stated in their documentation.

The actual requirements for a target are obtained by refining the
requirements of the project where the target is declared with the
explicitly specified requirements. The same is true for
usage-requirements. More details can be found in
link:#b2.reference.variants.proprefine[the section called “Property refinement”].

=== Name

The name of main target has two purposes. First, it's used to refer to
this target from other targets and from command line. Second, it's used
to compute the names of the generated files. Typically, filenames are
obtained from main target name by appending system-dependent suffixes
and prefixes.

The name of a main target can contain alphanumeric characters, dashes,
underscores and dots. The entire name is significant when resolving
references from other targets. For determining filenames, only the part
before the first dot is taken. For example:

[source]
----
obj test.release : test.cpp : <variant>release ;
obj test.debug : test.cpp : <variant>debug ;
----

will generate two files named `test.obj` (in two different directories),
not two files named `test.release.obj` and `test.debug.obj`.

=== Sources

The list of sources specifies what should be processed to get the
resulting targets. Most of the time, it's just a list of files.
Sometimes, you'll want to automatically construct the list of source
files rather than having to spell it out manually, in which case you can
use the link:#b2.reference.rules.glob[glob] rule. Here are two
examples:

[source]
----
exe a : a.cpp ; <1>
exe b : [ glob *.cpp ] ; <2>
----
<1> `a.cpp` is the only source file
<2> all `.cpp` files in this directory are sources

Unless you specify a file with an absolute path, the name is considered
relative to the source directory — which is typically the directory
where the Jamfile is located, but can be changed as described in
link:#b2.overview.projects.attributes.projectrule[the section called “Projects”].

The list of sources can also refer to other main targets. Targets in the
same project can be referred to by name, while targets in other projects
must be qualified with a directory or a symbolic project name. The
directory/project name is separated from the target name by a double
forward slash. There is no special syntax to distinguish the directory
name from the project name—the part before the double slash is first
looked up as project name, and then as directory name. For example:

[source]
----
lib helper : helper.cpp ;
exe a : a.cpp helper ;
exe b : b.cpp ..//utils ; <1>
exe c : c.cpp /boost/program_options//program_options ;
----
<1> Since all project ids start with slash, "`..`" is a directory name.

The first exe uses the library defined in the same project. The second
one uses some target (most likely a library) defined by a Jamfile one
level higher. Finally, the third target uses a http://boost.org[{CPP}
Boost] library, referring to it using its absolute symbolic name. More
information about target references can be found in
link:#b2.tutorial.libs[the section called “Dependent Targets”] and
link:#b2.reference.ids[the section called “Target identifiers and references”].

[[b2.overview.targets.requirements]]
=== Requirements

Requirements are the properties that should always be present when
building a target. Typically, they are includes and defines:

[source]
----
exe hello : hello.cpp : <include>/opt/boost <define>MY_DEBUG ;
----

There are a number of other features, listed in
link:#b2.overview.builtins.features[the section called “Builtin features”].
For example if a library can only be built statically, or a file can't be
compiled with optimization due to a compiler bug, one can use.

[source]
----
lib util : util.cpp : <link>static ;
obj main : main.cpp : <optimization>off ;
----

[[b2.overview.targets.requirements.conditional]]Sometimes, particular
relationships need to be
maintained among a target's build properties. This can be achieved with
_conditional requirements_. For example, you might want to set specific
`#defines` when a library is built as shared, or when a target's
`release` variant is built in release mode.

[source]
----
lib network : network.cpp
    : <link>shared:<define>NETWORK_LIB_SHARED
     <variant>release:<define>EXTRA_FAST
    ;
----

In the example above, whenever `network` is built with `<link>shared`,
`<define>NETWORK_LIB_SHARED` will be in its properties, too.

You can use several properties in the condition, for example:

[source]
----
lib network : network.cpp
    : <toolset>gcc,<optimization>speed:<define>USE_INLINE_ASSEMBLER
    ;
----

A more powerful variant of conditional requirements
is _indirect conditional_ requirements. You can provide a rule that will
be called with the current build properties and can compute additional
properties to be added. For example:

[source]
----
lib network : network.cpp
    : <conditional>@my-rule
    ;
rule my-rule ( properties * )
{
    local result ;
    if <toolset>gcc <optimization>speed in $(properties)
    {
        result += <define>USE_INLINE_ASSEMBLER ;
    }
    return $(result) ;
}
----

This example is equivalent to the previous one, but for complex cases,
indirect conditional requirements can be easier to write and understand.

Requirements explicitly specified for a target are usually combined with
the requirements specified for the containing project. You can cause a
target to completely ignore a specific project requirement using the
syntax by adding a minus sign before the property, for example:

[source]
----
exe main : main.cpp : -<define>UNNECESSARY_DEFINE ;
----

This syntax is the only way to ignore free properties, such as defines,
from a parent. It can be also useful for ordinary properties. Consider
this example:

[source]
----
project test : requirements <threading>multi ;
exe test1 : test1.cpp ;
exe test2 : test2.cpp : <threading>single ;
exe test3 : test3.cpp : -<threading>multi ;
----

Here, `test1` inherits the project requirements and will always be built
in multi-threaded mode. The `test2` target _overrides_ the project's
requirements and will always be built in single-threaded mode. In
contrast, the `test3` target _removes_ a property from the project
requirements and will be built either in single-threaded or
multi-threaded mode depending on which variant is requested by the user.

Note that the removal of requirements is completely textual: you need to
specify exactly the same property to remove it.

=== Default Build

The `default-build` parameter is a set of properties to be used if the
build request does not otherwise specify a value for features in the
set. For example:

[source]
----
exe hello : hello.cpp : : <threading>multi ;
----

would build a multi-threaded target unless the user explicitly requests
a single-threaded version. The difference between the requirements and
the default-build is that the requirements cannot be overridden in any
way.

=== Additional Information

The ways a target is built can be so different that describing them
using conditional requirements would be hard. For example, imagine that
a library actually uses different source files depending on the toolset
used to build it. We can express this situation using _target alternatives_:

[source]
----
lib demangler : dummy_demangler.cpp ;                # alternative 1
lib demangler : demangler_gcc.cpp : <toolset>gcc ;   # alternative 2
lib demangler : demangler_msvc.cpp : <toolset>msvc ; # alternative 3
----

In the example above, when built with `gcc` or `msvc`, `demangler` will
use a source file specific to the toolset. Otherwise, it will use a
generic source file, `dummy_demangler.cpp`.

It is possible to declare a target inline, i.e. the "sources" parameter
may include calls to other main rules. For example:

[source]
----
exe hello : hello.cpp
    [ obj helpers : helpers.cpp : <optimization>off ] ;
----

Will cause "helpers.cpp" to be always compiled without optimization.
When referring to an inline main target, its declared name must be
prefixed by its parent target's name and two dots. In the example above,
to build only helpers, one should run `b2 hello..helpers`.

When no target is requested on the command line, all targets in the
current project will be built. If a target should be built only by
explicit request, this can be expressed by the
link:#b2.reference.rules.explicit[explicit] rule:

[source]
----
explicit install_programs ;
----

[[b2.overview.projects]]
== Projects

As mentioned before, targets are grouped into projects, and each Jamfile
is a separate project. Projects are useful because they allow us to
group related targets together, define properties common to all those
targets, and assign a symbolic name to the project that can be used in
referring to its targets.

Projects are named using the `project` rule, which has the following
syntax:

[source]
----
project id : attributes ;
----

Here, _attributes_ is a sequence of rule arguments, each of which begins
with an attribute-name and is followed by any number of build
properties. The list of attribute names along with its handling is also
shown in the table below. For example, it is possible to write:

[source]
----
project tennis
    : requirements <threading>multi
    : default-build release
    ;
----

The possible attributes are listed below.

_Project id_ is a short way to denote a project, as opposed to the
Jamfile's pathname. It is a hierarchical path, unrelated to filesystem,
such as "boost/thread". link:#b2.reference.ids[Target references] make
use of project ids to specify a target.

_Source location_ specifies the directory where sources for the project
are located.

_Project requirements_ are requirements that apply to all the targets in
the projects as well as all sub-projects.

_Default build_ is the build request that should be used when no build
request is specified explicitly.

[[b2.overview.projects.attributes.projectrule]]
The default values for those attributes are given in the table below.

[cols=",,,",options="header",]
|===
|Attribute |Name |Default value |Handling by the `project` rule

|Project id |none |none |Assigned from the first parameter of the
'project' rule. It is assumed to denote absolute project id.

|Source location |`source-location` |The location of jamfile for the
project |Sets to the passed value

|Requirements |`requirements` |The parent's requirements |The parent's
requirements are refined with the passed requirement and the result is
used as the project requirements.

|Default build |`default-build` |none |Sets to the passed value

|Build directory |`build-dir` |Empty if the parent has no build
directory set. Otherwise, the parent's build directory with the relative
path from parent to the current project appended to it. |Sets to the
passed value, interpreted as relative to the project's location.
|===

Besides defining projects and main targets, Jamfiles often invoke
various utility rules. For the full list of rules that can be directly
used in Jamfile see
link:#b2.reference.rules[the section called “Builtin rules”].

Each subproject inherits attributes, constants and rules from its parent
project, which is defined by the nearest Jamfile in an ancestor
directory above the subproject. The top-level project is declared in a
file called `Jamroot`, or `Jamfile`. When loading a project,
B2 looks for either `Jamroot` or `Jamfile`. They are handled
identically, except that if the file is called `Jamroot`, the search for
a parent project is not performed. A `Jamfile` without a parent project
is also considered the top-level project.

Even when building in a subproject directory, parent project files are
always loaded before those of their sub-projects, so that every
definition made in a parent project is always available to its children.
The loading order of any other projects is unspecified. Even if one
project refers to another via the `use-project` or a target reference,
no specific order should be assumed.

NOTE: Giving the root project the special name “`Jamroot`” ensures that
B2 won't misinterpret a directory above it as the project root
just because the directory contains a Jamfile.

[[b2.overview.build_process]]
== The Build Process

When you've described your targets, you want B2 to run the
right tools and create the needed targets. This section will describe
two things: how you specify what to build, and how the main targets are
actually constructed.

The most important thing to note is that in B2, unlike other
build tools, the targets you declare do not correspond to specific
files. What you declare in a Jamfile is more like a “metatarget.”
Depending on the properties you specify on the command line, each
metatarget will produce a set of real targets corresponding to the
requested properties. It is quite possible that the same metatarget is
built several times with different properties, producing different
files.

TIP: This means that for B2, you cannot directly obtain a build
variant from a Jamfile. There could be several variants requested by the
user, and each target can be built with different properties.

[[b2.overview.build_request]]
=== Build Request

The command line specifies which targets to build and with which
properties. For example:

[source,shell]
----
b2 app1 lib1//lib1 toolset=gcc variant=debug optimization=full
----

would build two targets, "app1" and "lib1//lib1" with the specified
properties. You can refer to any targets, using
link:#b2.reference.ids[target id] and specify arbitrary properties.
Some of the properties are very common, and for them the name of the
property can be omitted. For example, the above can be written as:

[source,shell]
----
b2 app1 lib1//lib1 gcc debug optimization=full
----

The complete syntax, which has some additional shortcuts, is described
in link:#b2.overview.invocation[the section called “Invocation”].

=== Building a main target

When you request, directly or indirectly, a build of a main target with
specific requirements, the following steps are done. Some brief
explanation is provided, and more details are given in
link:#b2.reference.buildprocess[the section called “Build process”].

1.  Applying default build. If the default-build property of a target
specifies a value of a feature that is not present in the build request,
that value is added.
2.  Selecting the main target alternative to use. For each alternative
we look how many properties are present both in alternative's
requirements, and in build request. The alternative with largest number
of matching properties is selected.
3.  Determining "common" properties. The build request is
link:#b2.reference.variants.proprefine[refined] with target's
requirements. The conditional properties in requirements are handled as
well. Finally, default values of features are added.
4.  Building targets referred by the sources list and dependency
properties. The list of sources and the properties can refer to other
target using link:#b2.reference.ids[target references]. For each
reference, we take all
link:#b2.reference.features.attributes.propagated[propagated]
properties, refine them by explicit properties specified in the target
reference, and pass the resulting properties as build request to the
other target.
5.  Adding the usage requirements produced when building dependencies to
the "common" properties. When dependencies are built in the previous
step, they return both the set of created "real" targets, and usage
requirements. The usage requirements are added to the common properties
and the resulting property set will be used for building the current
target.
6.  Building the target using generators. To convert the sources to the
desired type, B2 uses "generators" -- objects that correspond
to tools like compilers and linkers. Each generator declares what type
of targets it can produce and what type of sources it requires. Using
this information, B2 determines which generators must be run to
produce a specific target from specific sources. When generators are
run, they return the "real" targets.
7.  Computing the usage requirements to be returned. The conditional
properties in usage requirements are expanded and the result is
returned.

=== Building a Project

Often, a user builds a complete project, not just one main target. In
fact, invoking `b2` without arguments builds the project defined in the
current directory.

When a project is built, the build request is passed without
modification to all main targets in that project. It's is possible to
prevent implicit building of a target in a project with the `explicit`
rule:

[source]
----
explicit hello_test ;
----

would cause the `hello_test` target to be built only if explicitly
requested by the user or by some other target.

The Jamfile for a project can include a number of `build-project` rule
calls that specify additional projects to be built.
