Skip to main content

cxx_precompiled_header

A cxx_precompiled_header rule specifies a single header file that can be precompiled and made available for use in other build rules such as a cxx_library() or a cxx_binary().

Details

This header file is precompiled by the preprocessor on behalf of the C, C++, Objective-C, or Objective-C++ rule using it, via its precompiled_header parameter. Afterwards the precompiled header is applied during the rule's own compilation (often with an appreciable reduction in build time, the main benefit of PCH).

This PCH is built once per combination of build flags which might affect the PCH's compatibility. For example, a distinct pre-compilation of the header occurs per combination of flags related to optimization, debug, architecture, and so on, used by rules which employ PCH. The flags used during the build of the dependent rule (that is, the "PCH-using rule") are in effect while building the PCH itself. Similarly, to the same end, the include paths used when building the PCH are applied to the dependent rule. For example, deps in the PCH rule are propagated back to the dependent rule, and the PCH's header search paths (e.g. -I or -isystem options) are prefixed onto the list of include paths for the dependent rule.

Function Signature

def cxx_precompiled_header(
*,
name: str,
default_target_platform: None | str = None,
target_compatible_with: list[str] = [],
compatible_with: list[str] = [],
exec_compatible_with: list[str] = [],
visibility: list[str] = [],
within_view: list[str] = ["PUBLIC"],
metadata: OpaqueMetadata = {},
tests: list[str] = [],
modifiers: OpaqueMetadata = [],
_apple_platforms: dict[str, str] = {},
_create_third_party_build_root: str = "prelude//third-party/tools:create_build",
_cxx_hacks: str = "prelude//cxx/tools:cxx_hacks",
_cxx_toolchain: str = "gh_facebook_buck2_shims_meta//:cxx",
_is_building_android_binary: bool = select({"prelude//os:building_android_binary": True, "DEFAULT": False}),
_meta_apple_library_validation_enabled: bool = False,
allow_cache_upload: None | bool = None,
archive_allow_cache_upload: bool = False,
auto_link_groups: bool = False,
bridging_header: None | str = None,
can_be_asset: None | bool = None,
compile_pch_file: bool = False,
compiler_flags: list[str] = [],
contacts: list[str] = [],
coverage_instrumentation_compiler_flags: list[str] = [],
cuda_compile_style: str = "mono",
cxx_runtime_type: None | str = None,
default_host_platform: None | str = None,
default_platform: None | str = None,
defaults: dict[str, str] = {},
deffile: None | str = None,
deps: list[str] = [],
deps_query: None | str = None,
devirt_enabled: bool = False,
diagnostics: dict[str, str] = {},
executable_name: None | str = None,
export_header_unit: None | str = None,
export_header_unit_filter: list[str] = [],
exported_deps: list[str] = [],
exported_header_style: str = "local",
exported_headers: list[str] | dict[str, str] = [],
exported_lang_platform_preprocessor_flags: dict[str, list[(str, list[str])]] = {},
exported_lang_preprocessor_flags: dict[str, list[str]] = {},
exported_linker_flags: list[str] = [],
exported_needs_coverage_instrumentation: bool = False,
exported_platform_deps: list[(str, list[str])] = [],
exported_platform_headers: list[(str, list[str] | dict[str, str])] = [],
exported_platform_linker_flags: list[(str, list[str])] = [],
exported_platform_preprocessor_flags: list[(str, list[str])] = [],
exported_post_linker_flags: list[str] = [],
exported_post_platform_linker_flags: list[(str, list[str])] = [],
exported_preprocessor_flags: list[str] = [],
extra_dwp_flags: list[str] = [],
extra_xcode_files: list[str] = [],
extra_xcode_sources: list[str] = [],
fat_lto: bool = False,
focused_list_target: None | str = None,
force_static: None | bool = None,
frameworks: list[str] = [],
header_mode: None | str = None,
header_namespace: None | str = None,
headers: list[str] | dict[str, str] = [],
headers_as_raw_headers_mode: None | str = None,
include_directories: list[str] = [],
include_in_android_merge_map_output: bool = True,
labels: list[str] = [],
lang_compiler_flags: dict[str, list[str]] = {},
lang_platform_compiler_flags: dict[str, list[(str, list[str])]] = {},
lang_platform_preprocessor_flags: dict[str, list[(str, list[str])]] = {},
lang_preprocessor_flags: dict[str, list[str]] = {},
libraries: list[str] = [],
licenses: list[str] = [],
link_deps_query_whole: bool = False,
link_execution_preference: None | str = None,
link_group: None | str = None,
link_group_map: None | str | list[(str, list[(None | str | list[None | str], str, None | str | list[str], None | str)], None | dict[str, typing.Any])] = None,
link_ordering: None | str = None,
link_style: None | str = None,
link_whole: None | bool = None,
linker_extra_outputs: list[str] = [],
linker_flags: list[str] = [],
local_linker_flags: list[str] = [],
module_name: None | str = None,
pch_clanguage: None | str = None,
platform_compiler_flags: list[(str, list[str])] = [],
platform_deps: list[(str, list[str])] = [],
platform_headers: list[(str, list[str] | dict[str, str])] = [],
platform_linker_flags: list[(str, list[str])] = [],
platform_preprocessor_flags: list[(str, list[str])] = [],
platform_srcs: list[(str, list[str | (str, list[str])])] = [],
post_linker_flags: list[str] = [],
post_platform_linker_flags: list[(str, list[str])] = [],
precompiled_header: None | str = None,
prefer_stripped_objects: bool = False,
preferred_linkage: str = "any",
prefix_header: None | str = None,
preprocessor_flags: list[str] = [],
public_include_directories: list[str] = [],
public_system_include_directories: list[str] = [],
raw_headers: list[str] = [],
raw_headers_as_headers_mode: None | str = None,
reexport_all_header_dependencies: None | bool = None,
resources: list[str] | dict[str, str] = [],
sdk_modules: list[str] = [],
separate_debug_info: bool = False,
soname: None | str = None,
src: str,
srcs: list[str | (str, list[str])] = [],
static_library_basename: None | str = None,
stub: bool = False,
supported_platforms_regex: None | str = None,
supports_header_symlink_subtarget: bool = False,
supports_merged_linking: None | bool = None,
supports_python_dlopen: None | bool = None,
supports_shlib_interfaces: bool = True,
thin_lto: bool = False,
third_party_project: None | str = None,
use_archive: None | bool = None,
use_content_based_paths: bool = True,
use_fbcc_rust_wrapper: bool = False,
use_header_units: bool = False,
used_by_wrap_script: bool = False,
uses_cxx_explicit_modules: bool = False,
uses_explicit_modules: bool = False,
version: None | str = None,
version_universe: None | str = None,
weak_framework_names: list[str] = [],
) -> None

Parameters

  • name: (required)

    name of the target

  • default_target_platform: (defaults to: None)

    specifies the default target platform, used when no platforms are specified on the command line

  • target_compatible_with: (defaults to: [])

    a list of constraints that are required to be satisfied for this target to be compatible with a configuration

  • compatible_with: (defaults to: [])

    a list of constraints that are required to be satisfied for this target to be compatible with a configuration

  • exec_compatible_with: (defaults to: [])

    a list of constraints that are required to be satisfied for this target to be compatible with an execution platform

  • visibility: (defaults to: [])

    a list of visibility patterns restricting what targets can depend on this one

  • within_view: (defaults to: ["PUBLIC"])

    a list of visibility patterns restricting what this target can depend on

  • metadata: (defaults to: {})

    a key-value map of metadata associated with this target

  • tests: (defaults to: [])

    a list of targets that provide tests for this one

  • modifiers: (defaults to: [])

    an array of modifiers associated with this target

  • allow_cache_upload: (defaults to: None)

    Whether to allow uploading the output of this rule to be uploaded to cache when the action is executed locally if the configuration allows (i.e. there is a cache configured and the client has permission to write to it).

  • compile_pch_file: (defaults to: False)

    Whether to compile the precompiled header file or use legacy mode.

  • compiler_flags: (defaults to: [])

    Flags to use when compiling any of the above sources (which require compilation).

  • deffile: (defaults to: None)

    Specifies the *.def file used on windows to modify a dll's exports in place of explicit __declspec(dllexport) declarations. The default is to not use a defile.

  • export_header_unit: (defaults to: None)

    If not None, export a C++20 header unit visible to dependants (including recursively) with use_header_units set to True.

    "include": replace includes of each file in exported_headers or raw_headers with an import of the precompiled header unit; files that do not include any of those headers do not load the header unit.

    "preload": automatically load the precompiled header unit in any dependant that uses header units.

  • export_header_unit_filter: (defaults to: [])

    A list of regexes. Each regex should match a set of headers in exported_headers or raw_headers to be precompiled together into one C++20 header unit.

    When used with export_header_unit="include", this allows different subsets of headers to be loaded only by files that use them. Each group should only depend on headers in previous groups.

    If a header is not matched by any group, it is not precompiled and will be included textually. If no filter is specified, the rule excludes inline headers based on a name heuristics (e.g. "-inl.h").

  • exported_deps: (defaults to: [])

    Dependencies that will also appear to belong to any rules that depend on this one. This has two effects: * Exported dependencies will also be included in the link line of dependents of this rules, but normal dependencies will not. * When reexport_all_header_dependencies = False, only exported headers of the rules specified here are re-exported.

  • exported_header_style: (defaults to: "local")

    How dependents should include exported headers from this rule. Can be either local (e.g. -I) or system (e.g. -isystem).

  • exported_headers: (defaults to: [])

    The set of header files that are made available for inclusion to the source files in the target and all targets that transitively depend on it. These should be specified as either a list of header files or a dictionary of header names to header files. The headers can be included with #include "$HEADER_NAMESPACE/$HEADER_NAME" or #include <$HEADER_NAMESPACE/$HEADER_NAME>, where $HEADER_NAMESPACE is the value of the target's header_namespace attribute, and $HEADER_NAME is the header name if specified, and the filename of the header file otherwise. Note that the header name can contain forward slashes (/). See header_namespace for more information.

  • exported_lang_platform_preprocessor_flags: (defaults to: {})

    Just as lang_platform_preprocessor_flags, but these flags also apply to rules that transitively depend on this rule.

  • exported_lang_preprocessor_flags: (defaults to: {})

    Just as lang_preprocessor_flags, but these flags also apply to rules that transitively depend on this rule.

  • exported_linker_flags: (defaults to: [])

    Flags to add to the linker command line when the output from this rule, or the output from any rule that transitively depends on this rule, is used in a link operation.

  • exported_platform_deps: (defaults to: [])

    Platform specific dependencies that will also appear to belong to any rules that depend on this one. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is a list of external dependencies (same format as exported_deps) that are exported if the platform matches the regex. See exported_deps for more information.

  • exported_platform_headers: (defaults to: [])

    Platform specific header files. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is either a list of header files or a dictionary of header names to header files that will be made available for inclusion to the source files in the target and all targets that transitively depend on it if the platform matches the regex. See headers for more information.

  • exported_platform_linker_flags: (defaults to: [])

    Platform-specific linker flags for this rule and for all rules that transitively depend on this rule. This argument is specified as a list of pairs where the first element in each pair is an un-anchored regex against which the platform name is matched. The regex should use java.util.regex.Pattern syntax. The second element in each pair is a list of linker flags. If the regex matches the platform, these flags are added to the linker command line when the output from this rule, or the output from any rule that transitively depends on this rule, is used in a link operation.

  • exported_platform_preprocessor_flags: (defaults to: [])

    Platform specific exported preprocessor flags. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is a list of flags to use when preprocessing the source files in the target and all targets that transitively depend on it if the platform matches the regex. See exported_preprocessor_flags for more information.

  • exported_post_linker_flags: (defaults to: [])

    Flags to add to the linker command line when the output from this rule, or the output from any rule that transitively depends on this rule, is used in a link operation—with the additional feature that these flags are guaranteed to be placed after the compiled object (.o) files on the linker command line.

  • exported_post_platform_linker_flags: (defaults to: [])

    Platform-specific linker flags for this rule and for all rules that transitively depend on this rule—and that are guaranteed to be placed after the compiled object (.o) files on the linker command line. In other respects, the syntax and semantics of this argument are the same as for the exported_platform_linker_flags argument.

  • extra_xcode_files: (defaults to: [])

    When the project is generated, this is the list of files that will added to the project. Those files won't be added to the build phase "Compile Sources".

  • extra_xcode_sources: (defaults to: [])

    When the project is generated, this is the list of files that will added to the build phase "Compile Sources" of the given target.

  • header_namespace: (defaults to: None)

    A path prefix when including headers of this target. Defaults to the path from the root of the repository to the directory where this target is defined. Can contain forward slashes (/), but cannot start with one. See headers for more information.

  • headers: (defaults to: [])

    The set of header files that are made available for inclusion to the source files in this target. These should be specified as either a list of header files or a dictionary of header names to header files. The header name can contain forward slashes (/). The headers can be included with #include "$HEADER_NAMESPACE/$HEADER_NAME" or #include <$HEADER_NAMESPACE/$HEADER_NAME> , where $HEADER_NAMESPACE is the value of the target's header_namespace attribute, and $HEADER_NAME is the header name if specified, and the filename of the header file otherwise. See header_namespace for more information.

  • include_directories: (defaults to: [])

    A list of include directories (with raw_headers) to be added to the compile command for compiling this target (via -I). An include directory is relative to the current package.

  • lang_compiler_flags: (defaults to: {})

    Language-specific compiler flags. These should be specified as a map of C-family language short names to lists of flags and is used to target flags to sources files for a specific language in the C-family (C, C++, assembler, etc.). The keys in the map can be: * cpp-output for C * c++-cpp-output for C++ * objective-c-cpp-output for Objective-C * objective-c++-cpp-output for Objective-C++ * cuda-cpp-output for Cuda * assembler for Assembly * asm for ASM

  • lang_platform_compiler_flags: (defaults to: {})

    Language- and platform-specific compiler flags. These should be specified as a map of C-family language short names, as described in lang_compiler_flags, to lists of pairs, as described in platform_compiler_flags.

  • lang_platform_preprocessor_flags: (defaults to: {})

    Language- and platform-specific preprocessor flags. These should be specified as a map of C-family language short names, as described in lang_preprocessor_flags, to lists of pairs, as described in platform_preprocessor_flags.

  • lang_preprocessor_flags: (defaults to: {})

    Language-specific preprocessor flags. These should be specified as a map of C-family language short names to lists of flags and is used to target flags to sources files for a specific language in the C-family (C, C++, assembler, etc.). The keys in the map can be: * c for C * c++ for C++ * objective-c for Objective-C * objective-c++ for Objective-C++ * cuda for Cuda * assembler-with-cpp for Assembly * asm-with-cpp for ASM

  • link_execution_preference: (defaults to: None)

    The execution preference for linking. Options are:

    • any : No preference is set, and the link action will be performed based on buck2's executor configuration.
    • full_hybrid : The link action will execute both locally and remotely, regardless of buck2's executor configuration (if the executor is capable of hybrid execution). The use_limited_hybrid setting of the hybrid executor is ignored.
    • local : The link action will execute locally if compatible on current host platform.
    • local_only : The link action will execute locally, and error if the current platform is not compatible.
    • remote : The link action will execute remotely if a compatible remote platform exists, otherwise locally.

    The default is None, expressing that no preference has been set on the target itself.

  • link_style: (defaults to: None)

    Determines whether to build and link this rule's dependencies statically or dynamically. Can be either static, static_pic or shared.

  • linker_extra_outputs: (defaults to: [])

    Declares extra outputs that the linker emits. These identifiers can be used in $(output ...) macros in linker_flags to interpolate the output path into the linker command line. Useful for custom linkers that emit extra output files.

  • linker_flags: (defaults to: [])

    Flags to add to the linker command line whenever the output from this rule is used in a link operation, such as linked into an executable or a shared library.

  • local_linker_flags: (defaults to: [])

    Flags to add to the linker command line whenever the output from this rule is used in a link operation driven by this rule (e.g. when this rule links a shared library, but not when the output is linked into a shared library by another rule's link group links).

  • pch_clanguage: (defaults to: None)

    The c-language extension to use for the precompiled header. Eg. .c, .cpp, .m, .mm, etc.

  • platform_compiler_flags: (defaults to: [])

    Platform specific compiler flags. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is a list of flags to use when compiling the target's sources. See compiler_flags for more information.

  • platform_headers: (defaults to: [])

    Platform specific header files. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is either a list of header files or a dictionary of header names to header files that will be made available for inclusion to the source files in the target if the platform matches the regex. See headers for more information.

  • platform_linker_flags: (defaults to: [])

    Platform-specific linker flags. This argument is specified as a list of pairs where the first element in each pair is an un-anchored regex against which the platform name is matched. The regex should use java.util.regex.Pattern syntax. The second element in each pair is a list of linker flags. If the regex matches the platform, these flags are added to the linker command line when the output from this rule is used in a link operation.

  • platform_preprocessor_flags: (defaults to: [])

    Platform specific preprocessor flags. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is a list of flags to use when preprocessing the target's sources. See preprocessor_flags for more information.

  • platform_srcs: (defaults to: [])

    Platform specific source files. These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched, and the second element is either a list of source files or a list of tuples of source files and a list of compilation flags to be preprocessed, compiled and assembled if the platform matches the regex. See srcs for more information.

  • preferred_linkage: (defaults to: "any")

    Determines what linkage is used when the library is depended on by another target. To control how the dependencies of this library are linked, use link_style instead.

  • preprocessor_flags: (defaults to: [])

    Flags to use when preprocessing any of the above sources (which require preprocessing).

  • public_include_directories: (defaults to: [])

    A list of include directories (with raw_headers) to be added to the compile command for compiling this target and every target that depends on it (via -I). An include directory is relative to the current package.

  • public_system_include_directories: (defaults to: [])

    A list of include directories (with raw_headers) to be added to the compile command for compiling this target and every target that depends on it (via -isystem if the compiler supports it of via -I otherwise). An include directory is relative to the current package.

  • raw_headers: (defaults to: [])

    The set of header files that can be used for inclusion to the source files in the target and all targets that transitively depend on it. Buck doesn't add raw headers to the search path of a compiler/preprocessor automatically. include_directories and public_include_directories are the recommended way to add raw headers to the search path (they will be added via -I). compiler_flags, preprocessor_flags and exported_preprocessor_flags can also be used to add such raw headers to the search path if inclusion via -isystem or -iquote is needed. raw_headers cannot be used together with headers or exported_headers in the same target.

  • raw_headers_as_headers_mode: (defaults to: None)

    Controls whether raw_headers and *include_directories attributes should be automatically converted to headers and symlink trees and/or header maps via headers. Only has an effect if the cxx_toolchain has explicitly opted into supporting this behavior via a non-default value, even if the value is disabled.

  • reexport_all_header_dependencies: (defaults to: None)

    Whether to automatically re-export the exported headers of all dependencies.

    When this is set to false, only exported headers from exported_deps are re-exported.

  • soname: (defaults to: None)

    Sets the soname ("shared object name") of any shared library produced from this rule. The default value is based on the full rule name. The macro $(ext) will be replaced with a platform-appropriate extension. An argument can be provided, which is a library version. For example soname = 'libfoo.$(ext 2.3)' will be libfoo.2.3.dylib on Mac and libfoo.so.2.3 on Linux.

  • src: (required)

    The path to the header file that should be precompiled. Only one header file can be specified. But of course this header could include any number of other headers. The included headers could belong to -- that is, be exported_headers from -- another rule, in which case, the rule would have to be added to deps as usual.

  • srcs: (defaults to: [])

    The set of C, C++, Objective-C, Objective-C++, or assembly source files to be preprocessed, compiled, and assembled by this rule. We determine which stages to run on each input source based on its file extension. See the GCC documentation for more detail on how file extensions are interpreted. Each element can be either a string specifying a source file (e.g. '') or a tuple of a string specifying a source file and a list of compilation flags (e.g. ('', ['-Wall', '-Werror']) ). In the latter case the specified flags will be used in addition to the rule's other flags when preprocessing and compiling that file (if applicable).

  • supported_platforms_regex: (defaults to: None)

    If present, an un-anchored regex (in java.util.regex.Pattern syntax) that matches all platforms that this library supports. It will not be built for other platforms.

  • use_fbcc_rust_wrapper: (defaults to: False)

    Opt-in for the rust version of the fbcode C++ Compiler wrapper (replacing the existing fbcc.py)

  • use_header_units: (defaults to: False)

    If True, makes any header unit exported by a dependency (including recursively) through export_header_unit available to the compiler. If false, the compilation ignores header units, regardless of what is exported by dependencies.

  • used_by_wrap_script: (defaults to: False)

    When using an exopackage Android, if this parameter is set to True, then the library is included in the primary APK even if native libraries would otherwise not be placed in it. This is intended for native libraries that are used by a wrap.sh script, which must be placed in the primary APK. Only one of can_be_asset and used_by_wrap_script can be set for a rule.

  • version: (defaults to: None)

    A string denoting a meaningful version of this rule that is optionally passed to the linker as extra metadata.

Examples

The best way to see how the cxx_precompiled_header() rule works is with an example. Let there be a header called common.h which has the following:



#pragma once

/* Include common C++ files. */
#include <string>
#include <map>
#include <set>
#include <type_traits>
#include <vector>

/* Some frequently-used headers from the Folly project. */
#include <folly/Conv.h>
#include <folly/Executor.h>
#include <folly/io/async/EventBase.h>




cxx_precompiled_header(
name = 'common_pch',
src = 'common.h',
deps = [
# Needed for standard C++ headers:
'//external/libcxx:headers',
# Needed for the Folly includes:
'//folly:folly',
'//folly/io/async:async',
],
)

cxx_binary(
name = 'main',
srcs = ['main.cpp'],
precompiled_header = ':common_pch',
deps = [ ... ],
compiler_flags = ['-g', '-O2', '-fPIC'],
)


The cxx_precompiled_header rule declares a precompiled header "template" containing the header file path, and dependencies. In this example we indicate that common.h is to be precompiled when used by another build rule.

Note that, by itself, this cxx_precompiled_header rule will not result in anything being built. The usage of this rule from another rule -- an "instantiation" of this precompiled header template -- is what will trigger the PCH build.

In the example above, the build for the binary named "main" will depend on the header being precompiled in a separate step, prior to compiling main.cpp, and the resulting PCH will be used in main's compilation.

The dependencies specified in this precompiled header rule's deps are transitive; they will propagate to rules using this PCH, so that during link time, any libraries which are required by the code made available in the header will be included in the final binary build.

The precompiled header dynamically created from the "template" will be built with flags which would be used in the dependent rule. In this case, main's use of specific compiler flags -g -O2 -fPIC will result in the production of a precompiled header with the same flags. This is so the precompiled code fully jives with rules using the PCH, i.e. they will have the same debug, optimization, CPU, etc. options. (The compiler is usually smart enough to reject a bad PCH, fortunately. But we want to ensure we take the appropriate steps to ensure we always have a PCH which works with any build that uses it.)

Another effect of a rule using a precompiled header is that the rule's list of build flags will change; not just to employ PCH with e.g. -include-pch (if using Clang), but also, to alter the sequence of header search paths. The rule using the precompiled header will "inherit" the lists of paths used during the PCH build, applying them first in its own search paths. This is to ensure that an #include directive will resolve in exactly the same way in this build as it would have in the PCH, to ensure full compatibility between the PCH and other rule's builds. For example, if the PCH were to use one version of stdcxx and another rule use a different version, the version differences won't clash, thereby avoiding different versions of the <cstring> header used between the precompiled header and the dependent rule, and preventing confused structure definitions, ABI incompatibility, and so on (catastrophe, in other words).