diff --git a/.github/workflows/pull-from-bazel-build.yml b/.github/workflows/pull-from-bazel-build.yml index fad7bc8..e3838be 100644 --- a/.github/workflows/pull-from-bazel-build.yml +++ b/.github/workflows/pull-from-bazel-build.yml @@ -31,22 +31,77 @@ jobs: steps: - uses: actions/checkout@v5 with: - # Don’t auto-init submodules + # Don't auto-init submodules submodules: false - name: Checkout submodules run: git submodule update --init -- upstream - + - name: Checkout commit of Bazel Build submodule if: ${{ inputs.bazelCommitHash != '' }} working-directory: upstream run: git checkout '${{ inputs.bazelCommitHash }}' + - name: Setup Bazel + uses: bazel-contrib/setup-bazel@0.15.0 + with: + bazelisk-cache: true + repository-cache: true + + - name: Build reference documentation + working-directory: upstream + run: > + bazel build + --config=docs + --build_metadata=ROLE=DOCS + --remote_header=x-buildbuddy-api-key=${{ secrets.BUILDBUDDY_ORG_API_KEY }} + --bes_results_url=https://app.buildbuddy.io/invocation/ + --bes_backend=grpcs://remote.buildbuddy.io + --remote_cache=grpcs://remote.buildbuddy.io + --remote_timeout=10m + //src/main/java/com/google/devtools/build/lib:gen_reference_docs + + # Upload reference-docs.zip as an artifact for debugging purposes + - name: Upload reference docs artifact + if: ${{ github.ref != 'refs/heads/main' }} + uses: actions/upload-artifact@v4.6.2 + with: + name: reference-docs + path: upstream/bazel-bin/src/main/java/com/google/devtools/build/lib/reference-docs.zip + retention-days: 7 + - name: Clean up mdx files run: ./cleanup-mdx.sh + - name: Set up Go + uses: actions/setup-go@v6 + with: + go-version: '1.25.2' + + - name: Initialize Go module for converter + run: | + cd html2md_converter + go mod init html-to-md-converter + go get github.com/JohannesKaufmann/html-to-markdown + + - name: Build HTML to Markdown converter + run: | + cd html2md_converter + go build -o html-to-md main.go + + - name: Convert reference documentation HTML to Markdown + run: | + # Extract and convert HTML reference docs to Markdown + ./html2md_converter/html-to-md \ + -zip upstream/bazel-bin/src/main/java/com/google/devtools/build/lib/reference-docs.zip \ + -output reference-docs-temp + - name: Transform upstream docs to mdx run: ./copy-upstream-docs.sh - name: Create versioned navigation run: ./docs.json.update.sh + + - name: Clean up temporary files + run: rm -rf reference-docs-temp + diff --git a/copy-upstream-docs.sh b/copy-upstream-docs.sh index a47108e..e45aa66 100755 --- a/copy-upstream-docs.sh +++ b/copy-upstream-docs.sh @@ -6,8 +6,15 @@ set -o errexit -o nounset -o pipefail -SOURCE_DIR="upstream/site/en" -DEST_DIR="${1:-.}" # Use first argument or current directory as default +# Primary upstream directory +UPSTREAM_SITE="upstream/site/en" + +# Reference docs directory +REFERENCE_DOCS="reference-docs-temp" + +# Destination directory (default to current directory) +DEST_DIR="${1:-.}" + # Files that live in this repo, not fetched from upstream LOCAL_FILES=" index.mdx @@ -43,6 +50,10 @@ query/language.mdx query/quickstart.mdx reference/flag-cheatsheet.mdx reference/test-encyclopedia.mdx +reference/command-line-reference.mdx +reference/be/be-nav.mdx +reference/be/functions.mdx +reference/be/platforms-and-toolchains.mdx release/rolling.mdx remote/ci.mdx remote/dynamic.mdx @@ -53,53 +64,56 @@ start/go.mdx tutorials/ccp-toolchain-config.mdx " -# Check if source directory exists -if [ ! -d "$SOURCE_DIR" ]; then - echo "Error: Source directory '$SOURCE_DIR' not found" +# Verify that at least one source exists +if [ ! -d "$UPSTREAM_SITE" ] && [ ! -d "$REFERENCE_DOCS" ]; then + echo "Error: neither source directory exists: '$UPSTREAM_SITE' or '$REFERENCE_DOCS'" exit 1 fi -# Create destination directory if it doesn't exist if [ ! -d "$DEST_DIR" ]; then echo "Creating destination directory: $DEST_DIR" mkdir -p "$DEST_DIR" fi -echo "Finding all .md files in $SOURCE_DIR and copying to $DEST_DIR..." - -# Find all .md files and copy them -find "$SOURCE_DIR" -name "*.md" -type f | while read -r source_file; do - # Get relative path from upstream/site/en - relative_path="${source_file#$SOURCE_DIR/}" - - # Convert .md to .mdx - target_file="${relative_path%.md}.mdx" - - # Create target directory if it doesn't exist - target_dir=$(dirname "$DEST_DIR/$target_file") - if [ "$target_dir" != "$DEST_DIR" ]; then - mkdir -p "$target_dir" +echo "Will search in '$UPSTREAM_SITE' and '$REFERENCE_DOCS' (if exists) to copy .md → .mdx to $DEST_DIR" + +transform_docs() { + local SOURCE_DIR="$1" + if [ ! -d "$SOURCE_DIR" ]; then + echo "Warning: source directory '$SOURCE_DIR' not found, skipping" + return fi - + + find "$SOURCE_DIR" -name "*.md" -type f | while read -r source_file; do + # Derive the relative path inside the source tree + relative_path="${source_file#$SOURCE_DIR/}" + target_file="${relative_path%.md}.mdx" + target_dir=$(dirname "$DEST_DIR/$target_file") + + mkdir -p "$target_dir" + # Check if this file is in the BROKEN_FILES list - if echo "$BROKEN_FILES" | grep -q "^$target_file$"; then - echo "Skipping broken file: $target_file" - continue - fi - + if echo "$BROKEN_FILES" | grep -q "^$target_file$"; then + echo "Skipping broken file: $target_file" + continue + fi + # Transform and copy the file echo "Transforming and copying $source_file to $DEST_DIR/$target_file" awk -f transform-docs.awk "$source_file" > "$DEST_DIR/$target_file" -done + done +} -echo "Successfully copied all .md files to .mdx files in $DEST_DIR" +# Copy from both sources +transform_docs "$UPSTREAM_SITE" +transform_docs "$REFERENCE_DOCS" -# Convert community YAML files to MDX echo "Converting community YAML files to MDX..." ./convert-community-to-mdx.sh "$DEST_DIR/community/experts" ./convert-community-to-mdx.sh "$DEST_DIR/community/partners" -# Copy community images to destination community/images/ -# We don't need to do this for images under a docs/ folder, so many other images already work +echo "Copying community images..." mkdir -p "$DEST_DIR/community/images" cp upstream/site/en/community/images/* "$DEST_DIR/community/images/" + +echo "Done copying docs." diff --git a/docs.json b/docs.json index 42a4f12..89ac54c 100644 --- a/docs.json +++ b/docs.json @@ -166,22 +166,17 @@ { "group": "Build encyclopedia", "pages": [ - "reference/be/overview", + "reference/be/c-cpp", "reference/be/common-definitions", + "reference/be/extra-actions", + "reference/be/general", + "reference/be/java", "reference/be/make-variables", - "reference/be/functions" - ] - }, - { - "group": "Command line reference", - "pages": [ - "reference/command-line-reference" - ] - }, - { - "group": "Query Language", - "pages": [ - "query/language" + "reference/be/objective-c", + "reference/be/overview", + "reference/be/protocol-buffer", + "reference/be/python", + "reference/be/shell" ] }, { @@ -191,9 +186,9 @@ ] }, { - "group": "Flag cheatsheet", + "group": "Skyframe", "pages": [ - "reference/flag-cheatsheet" + "reference/skyframe" ] } ] @@ -1648,23 +1643,23 @@ { "group": "Why Bazel?", "pages": [ - "7.6.1/about/intro", - "7.6.1/about/why", - "7.6.1/about/vision", - "7.6.1/about/roadmap", - "7.6.1/about/faq" + "7.6.2/about/intro", + "7.6.2/about/why", + "7.6.2/about/vision", + "7.6.2/about/roadmap", + "7.6.2/about/faq" ] }, { "group": "Build system basics", "pages": [ - "7.6.1/basics", - "7.6.1/basics/build-systems", - "7.6.1/basics/task-based-builds", - "7.6.1/basics/artifact-based-builds", - "7.6.1/basics/distributed-builds", - "7.6.1/basics/dependencies", - "7.6.1/basics/hermeticity" + "7.6.2/basics", + "7.6.2/basics/build-systems", + "7.6.2/basics/task-based-builds", + "7.6.2/basics/artifact-based-builds", + "7.6.2/basics/distributed-builds", + "7.6.2/basics/dependencies", + "7.6.2/basics/hermeticity" ] } ] @@ -1675,37 +1670,37 @@ { "group": "Install", "pages": [ - "7.6.1/install", - "7.6.1/install/bazelisk", - "7.6.1/install/os-x", - "7.6.1/install/windows", - "7.6.1/install/ubuntu", - "7.6.1/install/suse", - "7.6.1/install/docker-container", - "7.6.1/install/compile-source", - "7.6.1/install/completion", - "7.6.1/install/ide" + "7.6.2/install", + "7.6.2/install/bazelisk", + "7.6.2/install/os-x", + "7.6.2/install/windows", + "7.6.2/install/ubuntu", + "7.6.2/install/suse", + "7.6.2/install/docker-container", + "7.6.2/install/compile-source", + "7.6.2/install/completion", + "7.6.2/install/ide" ] }, { "group": "First build tutorials", "pages": [ - "7.6.1/start/cpp", - "7.6.1/start/java", - "7.6.1/start/android-app", - "7.6.1/start/ios-app" + "7.6.2/start/cpp", + "7.6.2/start/java", + "7.6.2/start/android-app", + "7.6.2/start/ios-app" ] }, { "group": "Concepts", "pages": [ - "7.6.1/concepts/build-ref", - "7.6.1/concepts/labels", - "7.6.1/concepts/build-files", - "7.6.1/concepts/dependencies", - "7.6.1/concepts/visibility", - "7.6.1/concepts/platforms", - "7.6.1/concepts/hermeticity" + "7.6.2/concepts/build-ref", + "7.6.2/concepts/labels", + "7.6.2/concepts/build-files", + "7.6.2/concepts/dependencies", + "7.6.2/concepts/visibility", + "7.6.2/concepts/platforms", + "7.6.2/concepts/hermeticity" ] } ] @@ -1716,72 +1711,72 @@ { "group": "Releases", "pages": [ - "7.6.1/release", - "7.6.1/release/rolling", - "7.6.1/release/backward-compatibility", - "7.6.1/release/rule-compatibility" + "7.6.2/release", + "7.6.2/release/rolling", + "7.6.2/release/backward-compatibility", + "7.6.2/release/rule-compatibility" ] }, { "group": "Basics", "pages": [ - "7.6.1/build/style-guide", - "7.6.1/build/share-variables", - "7.6.1/community/recommended-rules", - "7.6.1/run/build" + "7.6.2/build/style-guide", + "7.6.2/build/share-variables", + "7.6.2/community/recommended-rules", + "7.6.2/run/build" ] }, { "group": "Advanced", "pages": [ - "7.6.1/configure/attributes", - "7.6.1/configure/integrate-cpp", - "7.6.1/configure/coverage", - "7.6.1/configure/best-practices", - "7.6.1/configure/windows", - "7.6.1/advanced/performance/build-performance-metrics", - "7.6.1/advanced/performance/build-performance-breakdown", - "7.6.1/advanced/performance/json-trace-profile", - "7.6.1/advanced/performance/memory", - "7.6.1/advanced/performance/iteration-speed" + "7.6.2/configure/attributes", + "7.6.2/configure/integrate-cpp", + "7.6.2/configure/coverage", + "7.6.2/configure/best-practices", + "7.6.2/configure/windows", + "7.6.2/advanced/performance/build-performance-metrics", + "7.6.2/advanced/performance/build-performance-breakdown", + "7.6.2/advanced/performance/json-trace-profile", + "7.6.2/advanced/performance/memory", + "7.6.2/advanced/performance/iteration-speed" ] }, { "group": "Remote Execution", "pages": [ - "7.6.1/remote/rbe", - "7.6.1/remote/rules", - "7.6.1/remote/ci", - "7.6.1/remote/dynamic", - "7.6.1/remote/caching", - "7.6.1/remote/sandbox", - "7.6.1/remote/workspace", - "7.6.1/remote/cache-remote", - "7.6.1/remote/cache-local", - "7.6.1/remote/output-directories", - "7.6.1/remote/persistent", - "7.6.1/remote/multiplex", - "7.6.1/remote/creating", - "7.6.1/remote/bep", - "7.6.1/remote/bep-examples", - "7.6.1/remote/bep-glossary" + "7.6.2/remote/rbe", + "7.6.2/remote/rules", + "7.6.2/remote/ci", + "7.6.2/remote/dynamic", + "7.6.2/remote/caching", + "7.6.2/remote/sandbox", + "7.6.2/remote/workspace", + "7.6.2/remote/cache-remote", + "7.6.2/remote/cache-local", + "7.6.2/remote/output-directories", + "7.6.2/remote/persistent", + "7.6.2/remote/multiplex", + "7.6.2/remote/creating", + "7.6.2/remote/bep", + "7.6.2/remote/bep-examples", + "7.6.2/remote/bep-glossary" ] }, { "group": "Tutorials", "pages": [ - "7.6.1/tutorials/cpp-use-cases", - "7.6.1/tutorials/ccp-toolchain-config", - "7.6.1/tutorials/cpp-dependency", - "7.6.1/tutorials/cpp-labels" + "7.6.2/tutorials/cpp-use-cases", + "7.6.2/tutorials/ccp-toolchain-config", + "7.6.2/tutorials/cpp-dependency", + "7.6.2/tutorials/cpp-labels" ] }, { "group": "Migrate", "pages": [ - "7.6.1/migrate", - "7.6.1/migrate/maven", - "7.6.1/migrate/xcode" + "7.6.2/migrate", + "7.6.2/migrate/maven", + "7.6.2/migrate/xcode" ] } ] @@ -1792,34 +1787,34 @@ { "group": "Build encyclopedia", "pages": [ - "7.6.1/reference/be/overview", - "7.6.1/reference/be/common-definitions", - "7.6.1/reference/be/make-variables", - "7.6.1/reference/be/functions" + "7.6.2/reference/be/overview", + "7.6.2/reference/be/common-definitions", + "7.6.2/reference/be/make-variables", + "7.6.2/reference/be/functions" ] }, { "group": "Command line reference", "pages": [ - "7.6.1/reference/command-line-reference" + "7.6.2/reference/command-line-reference" ] }, { "group": "Query Language", "pages": [ - "7.6.1/query/language" + "7.6.2/query/language" ] }, { "group": "Glossary", "pages": [ - "7.6.1/reference/glossary" + "7.6.2/reference/glossary" ] }, { "group": "Flag cheatsheet", "pages": [ - "7.6.1/reference/flag-cheatsheet" + "7.6.2/reference/flag-cheatsheet" ] } ] @@ -1830,35 +1825,35 @@ { "group": "Concepts", "pages": [ - "7.6.1/extending/concepts" + "7.6.2/extending/concepts" ] }, { "group": "Writing rules", "pages": [ - "7.6.1/rules/rules-tutorial", - "7.6.1/rules/macro-tutorial", - "7.6.1/rules/legacy-macro-tutorial", - "7.6.1/rules/verbs-tutorial", - "7.6.1/rules/language", - "7.6.1/rules/bzl-style", - "7.6.1/rules/challenges", - "7.6.1/rules/windows" + "7.6.2/rules/rules-tutorial", + "7.6.2/rules/macro-tutorial", + "7.6.2/rules/legacy-macro-tutorial", + "7.6.2/rules/verbs-tutorial", + "7.6.2/rules/language", + "7.6.2/rules/bzl-style", + "7.6.2/rules/challenges", + "7.6.2/rules/windows" ] }, { "group": "Distributing rules", "pages": [ - "7.6.1/rules/testing", - "7.6.1/rules/performance", - "7.6.1/rules/deploying" + "7.6.2/rules/testing", + "7.6.2/rules/performance", + "7.6.2/rules/deploying" ] }, { "group": "APIs", "pages": [ - "7.6.1/rules/lib/overview", - "7.6.1/rules/lib/globals" + "7.6.2/rules/lib/overview", + "7.6.2/rules/lib/globals" ] } ] @@ -1869,36 +1864,36 @@ { "group": "Contributing", "pages": [ - "7.6.1/contribute", - "7.6.1/contribute/policy", - "7.6.1/contribute/patch-acceptance", - "7.6.1/contribute/maintainers-guide", - "7.6.1/contribute/codebase", - "7.6.1/contribute/search", - "7.6.1/contribute/statemachine-guide", - "7.6.1/contribute/docs", - "7.6.1/contribute/docs-style-guide", - "7.6.1/contribute/design-documents", - "7.6.1/contribute/release-notes" + "7.6.2/contribute", + "7.6.2/contribute/policy", + "7.6.2/contribute/patch-acceptance", + "7.6.2/contribute/maintainers-guide", + "7.6.2/contribute/codebase", + "7.6.2/contribute/search", + "7.6.2/contribute/statemachine-guide", + "7.6.2/contribute/docs", + "7.6.2/contribute/docs-style-guide", + "7.6.2/contribute/design-documents", + "7.6.2/contribute/release-notes" ] }, { "group": "Programs", "pages": [ - "7.6.1/community/update", - "7.6.1/community/sig", - "7.6.1/community/experts", - "7.6.1/community/partners", - "7.6.1/community/users", - "7.6.1/community/recommended-rules", - "7.6.1/community/remote-execution-services" + "7.6.2/community/update", + "7.6.2/community/sig", + "7.6.2/community/experts", + "7.6.2/community/partners", + "7.6.2/community/users", + "7.6.2/community/recommended-rules", + "7.6.2/community/remote-execution-services" ] }, { "group": "Getting help", "pages": [ - "7.6.1/help", - "7.6.1/contribute/policy" + "7.6.2/help", + "7.6.2/contribute/policy" ] } ] diff --git a/html2md_converter/main.go b/html2md_converter/main.go new file mode 100644 index 0000000..7bf9945 --- /dev/null +++ b/html2md_converter/main.go @@ -0,0 +1,169 @@ +package main + +import ( + "archive/zip" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + md "github.com/JohannesKaufmann/html-to-markdown" +) + +func main() { + zipPath := flag.String("zip", "", "Path to the zip file containing HTML files") + outputDir := flag.String("output", "output", "Output directory for markdown files") + flag.Parse() + + if *zipPath == "" { + fmt.Println("Error: -zip flag is required") + flag.Usage() + os.Exit(1) + } + + if err := convertZipToMarkdown(*zipPath, *outputDir); err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + + fmt.Println("Conversion completed successfully!") +} + +func convertZipToMarkdown(zipPath, outputDir string) error { + // Open the zip file + r, err := zip.OpenReader(zipPath) + if err != nil { + return fmt.Errorf("failed to open zip file: %w", err) + } + defer r.Close() + + // Create markdown converter + converter := md.NewConverter("", true, nil) + + // Process each file in the zip + for _, f := range r.File { + if err := processZipFile(f, outputDir, converter); err != nil { + return fmt.Errorf("failed to process %s: %w", f.Name, err) + } + } + + return nil +} + +func processZipFile(f *zip.File, outputDir string, converter *md.Converter) error { + // Skip directories + if f.FileInfo().IsDir() { + return nil + } + + // Handle markdown files - copy them as-is + if isMarkdownFile(f.Name) { + return copyMarkdownFile(f, outputDir) + } + + // Only process HTML files + if !isHTMLFile(f.Name) { + fmt.Printf("Skipping file: %s\n", f.Name) + return nil + } + + fmt.Printf("Processing: %s\n", f.Name) + + // Open the file from zip + rc, err := f.Open() + if err != nil { + return fmt.Errorf("failed to open file in zip: %w", err) + } + defer rc.Close() + + // Read HTML content + htmlBytes, err := io.ReadAll(rc) + if err != nil { + return fmt.Errorf("failed to read HTML content: %w", err) + } + + // Convert HTML to Markdown + markdown, err := converter.ConvertString(string(htmlBytes)) + if err != nil { + return fmt.Errorf("failed to convert HTML to markdown: %w", err) + } + + // Create output path (replace .html with .md) + outputPath := filepath.Join(outputDir, changeExtension(f.Name, ".md")) + + // Create directory structure + if err := os.MkdirAll(filepath.Dir(outputPath), 0755); err != nil { + return fmt.Errorf("failed to create output directory: %w", err) + } + + // Write markdown file + if err := os.WriteFile(outputPath, []byte(markdown), 0644); err != nil { + return fmt.Errorf("failed to write markdown file: %w", err) + } + + fmt.Printf(" -> Created: %s\n", outputPath) + return nil +} + +func isHTMLFile(filename string) bool { + ext := strings.ToLower(filepath.Ext(filename)) + return ext == ".html" || ext == ".htm" +} + +func isMarkdownFile(filename string) bool { + ext := strings.ToLower(filepath.Ext(filename)) + return ext == ".md" || ext == ".markdown" +} + +func isYAMLFile(filename string) bool { + ext := strings.ToLower(filepath.Ext(filename)) + return ext == ".yaml" || ext == ".yml" +} + +func copyMarkdownFile(f *zip.File, outputDir string) error { + fmt.Printf("Copying markdown file: %s\n", f.Name) + return copyFile(f, outputDir, f.Name) +} + +func copyYAMLFile(f *zip.File, outputDir string) error { + fmt.Printf("Copying YAML file: %s\n", f.Name) + return copyFile(f, outputDir, f.Name) +} + +func copyFile(f *zip.File, outputDir string, outputPath string) error { + // Open the file from zip + rc, err := f.Open() + if err != nil { + return fmt.Errorf("failed to open file in zip: %w", err) + } + defer rc.Close() + + // Read content + content, err := io.ReadAll(rc) + if err != nil { + return fmt.Errorf("failed to read content: %w", err) + } + + // Create output path + fullOutputPath := filepath.Join(outputDir, outputPath) + + // Create directory structure + if err := os.MkdirAll(filepath.Dir(fullOutputPath), 0755); err != nil { + return fmt.Errorf("failed to create output directory: %w", err) + } + + // Write file + if err := os.WriteFile(fullOutputPath, content, 0644); err != nil { + return fmt.Errorf("failed to write file: %w", err) + } + + fmt.Printf(" -> Created: %s\n", fullOutputPath) + return nil +} + +func changeExtension(filename, newExt string) string { + ext := filepath.Ext(filename) + return filename[:len(filename)-len(ext)] + newExt +} diff --git a/html_mdx_converter_test.sh b/html_mdx_converter_test.sh new file mode 100755 index 0000000..e5e4a04 --- /dev/null +++ b/html_mdx_converter_test.sh @@ -0,0 +1,88 @@ +#!/bin/bash + +# Local test script for HTML to Markdown converter +# This runs the converter in a Go Docker container + +set -e # Exit on error + +# Colors for output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +RED='\033[0;31m' +NC='\033[0m' # No Color + +echo -e "${BLUE}=== Testing HTML to Markdown Converter with Docker ===${NC}\n" + +# Check if Docker is running +if ! docker info > /dev/null 2>&1; then + echo -e "${RED}Error: Docker is not running. Please start Docker and try again.${NC}" + exit 1 +fi + +# Check if zip file exists +ZIP_FILE="${1:-reference-docs.zip}" +if [ ! -f "$ZIP_FILE" ]; then + echo -e "${RED}Error: Zip file '$ZIP_FILE' not found${NC}" + echo "Usage: $0 [path-to-zip-file]" + echo "Example: $0 upstream/bazel-bin/src/main/java/com/google/devtools/build/lib/reference-docs.zip" + exit 1 +fi + +# Get absolute path to zip file +ZIP_FILE_ABS=$(cd "$(dirname "$ZIP_FILE")" && pwd)/$(basename "$ZIP_FILE") + +echo -e "${GREEN}✓${NC} Found zip file: $ZIP_FILE_ABS" + +# Create output directory +OUTPUT_DIR="reference-docs-temp" +rm -rf "$OUTPUT_DIR" +mkdir -p "$OUTPUT_DIR" + +echo -e "${GREEN}✓${NC} Created output directory: $OUTPUT_DIR" + +# Run converter in Docker container +echo -e "\n${BLUE}Running converter in Go Docker container...${NC}\n" + +docker run --rm \ + -v "$(pwd)/html2md_converter:/app" \ + -v "$ZIP_FILE_ABS:/input/reference-docs.zip:ro" \ + -v "$(pwd)/$OUTPUT_DIR:/output" \ + -w /app \ + golang:1.21 \ + bash -c " + echo '==> Initializing Go module...' + go mod init html-to-md-converter + go get github.com/JohannesKaufmann/html-to-markdown + + echo '==> Building converter...' + go build -o html-to-md main.go + + echo '==> Running conversion...' + ./html-to-md -zip /input/reference-docs.zip -output /output + + echo '==> Done!' + " + +echo -e "\n${GREEN}✓${NC} Conversion complete!" + +# Show results +echo -e "\n${BLUE}=== Results ===${NC}" +echo "Output directory: $OUTPUT_DIR" +echo "" +echo "Directory structure:" +tree -L 3 "$OUTPUT_DIR" 2>/dev/null || find "$OUTPUT_DIR" -type f | head -20 + +echo -e "\n${BLUE}=== Sample converted file (before AWK) ===${NC}" +SAMPLE_FILE=$(find "$OUTPUT_DIR" -name "*.md" -type f | head -1) +if [ -n "$SAMPLE_FILE" ]; then + echo "File: $SAMPLE_FILE" + echo "---" + head -30 "$SAMPLE_FILE" + echo "..." +else + echo "No markdown files found" +fi + +# Run AWK transformation +./copy-upstream-docs.sh +rm -rf "$OUTPUT_DIR" diff --git a/install/ide.mdx b/install/ide.mdx index 4988feb..aa6210b 100644 --- a/install/ide.mdx +++ b/install/ide.mdx @@ -64,7 +64,8 @@ Features: through code, inspect variables, and so on) Find [the plugin on the Visual Studio -marketplace](https://marketplace.visualstudio.com/items?itemName=BazelBuild.vscode-bazel). +marketplace](https://marketplace.visualstudio.com/items?itemName=BazelBuild.vscode-bazel) +or the [OpenVSX marketplace](https://open-vsx.org/extension/BazelBuild/vscode-bazel). The plugin is [open source](https://github.com/bazelbuild/vscode-bazel). See also: [Autocomplete for Source Code](#autocomplete-for-source-code) diff --git a/templates/hugo_config.yaml.jinja2 b/legacy_devsite_to_hugo_converter/templates/hugo_config.yaml.jinja2 similarity index 100% rename from templates/hugo_config.yaml.jinja2 rename to legacy_devsite_to_hugo_converter/templates/hugo_config.yaml.jinja2 diff --git a/templates/section_index.jinja2 b/legacy_devsite_to_hugo_converter/templates/section_index.jinja2 similarity index 100% rename from templates/section_index.jinja2 rename to legacy_devsite_to_hugo_converter/templates/section_index.jinja2 diff --git a/reference/be/be-nav.mdx b/reference/be/be-nav.mdx new file mode 100644 index 0000000..fbf211d --- /dev/null +++ b/reference/be/be-nav.mdx @@ -0,0 +1,27 @@ +\*\*Build Encyclopedia\*\* +- [Overview](/reference/be/overview.html) +- [Concepts](#be-menu) - [Common Definitions](/reference/be/common-definitions.html) + - ["Make" variables](/reference/be/make-variables.html) +- [Rules](#be-rules) - [Functions](/reference/be/functions.html) + - [C / C++](/reference/be/c-cpp.html) + - [Java](/reference/be/java.html) + - [Objective-C](/reference/be/objective-c.html) + - [Protocol Buffer](/reference/be/protocol-buffer.html) + - [Python](/reference/be/python.html) + - [Shell](/reference/be/shell.html) + - [Extra Actions](/reference/be/extra-actions.html) + - [General](/reference/be/general.html) + - [Platforms and Toolchains](/reference/be/platforms-and-toolchains.html) + - [AppEngine](https://github.com/bazelbuild/rules_appengine) + - [Apple (Swift, iOS, macOS, tvOS, visionOS, watchOS)](https://github.com/bazelbuild/rules_apple) + - [C#](https://github.com/bazelbuild/rules_dotnet) + - [D](https://github.com/bazelbuild/rules_d) + - [Docker](https://github.com/bazelbuild/rules_docker) + - [Groovy](https://github.com/bazelbuild/rules_groovy) + - [Go](https://github.com/bazelbuild/rules_go) + - [JavaScript (Closure)](https://github.com/bazelbuild/rules_closure) + - [Jsonnet](https://github.com/bazelbuild/rules_jsonnet) + - [Packaging](/reference/be/pkg.html) + - [Rust](https://github.com/bazelbuild/rules_rust) + - [Sass](https://github.com/bazelbuild/rules_sass) + - [Scala](https://github.com/bazelbuild/rules_scala) diff --git a/reference/be/c-cpp.mdx b/reference/be/c-cpp.mdx new file mode 100644 index 0000000..01cacc9 --- /dev/null +++ b/reference/be/c-cpp.mdx @@ -0,0 +1,2460 @@ +--- +title: 'C / C++ Rules' +--- + + + +## Rules + +- [cc\_binary](#cc_binary) +- [cc\_import](#cc_import) +- [cc\_library](#cc_library) +- [cc\_shared\_library](#cc_shared_library) +- [cc\_static\_library](#cc_static_library) +- [cc\_test](#cc_test) +- [cc\_toolchain](#cc_toolchain) +- [fdo\_prefetch\_hints](#fdo_prefetch_hints) +- [fdo\_profile](#fdo_profile) +- [memprof\_profile](#memprof_profile) +- [propeller\_optimize](#propeller_optimize) + +## cc\_binary + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl) + +``` +cc_binary(name, deps, srcs, data, additional_linker_inputs, args, aspect_hints, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, distribs, dynamic_deps, env, exec_compatible_with, exec_group_compatible_with, exec_properties, features, hdrs_check, includes, licenses, link_extra_lib, linkopts, linkshared, linkstatic, local_defines, malloc, module_interfaces, nocopts, output_licenses, package_metadata, reexport_deps, restricted_to, stamp, tags, target_compatible_with, testonly, toolchains, visibility, win_def_file) +``` + +It produces an executable binary. + +The `name` of the target should be the same as the name of the +source file that is the main entry point of the application (minus the extension). +For example, if your entry point is in `main.cc`, then your name should +be `main`. + +#### Implicit output targets + +- `name.stripped` (only built if explicitly requested): A stripped + version of the binary. `strip -g` is run on the binary to remove debug + symbols. Additional strip options can be provided on the command line using + `--stripopt=-foo`. +- `name.dwp` (only built if explicitly requested): If + [Fission](https://gcc.gnu.org/wiki/DebugFission) is enabled: a debug + information package file suitable for debugging remotely deployed binaries. Else: an + empty file. + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + + The list of other libraries to be linked in to the binary target. + +These can be `cc_library` or `objc_library` +targets. + +It is also allowed to +put linker scripts (.lds) into deps, and reference them in +[linkopts](#cc_binary.linkopts). + `srcs` + +List of [labels](/concepts/labels); default is `[]` + + The list of C and C++ files that are processed to create the library target. +These are C/C++ source and header files, either non-generated (normal source +code) or generated. + +All `.cc`, `.c`, and `.cpp` files will +be compiled. These might be generated files: if a named file is in +the `outs` of some other rule, this `cc_library` +will automatically depend on that other rule. + +Pure assembler files (.s, .asm) are not preprocessed and are typically built using +the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built +using the C/C++ compiler. + +A `.h` file will not be compiled, but will be available for +inclusion by sources in this rule. Both `.cc` and +`.h` files can directly include headers listed in +these `srcs` or in the `hdrs` of this rule or any +rule listed in the `deps` argument. + +All `#include` d files must be mentioned in the +`hdrs` attribute of this or referenced `cc_library` +rules, or they should be listed in `srcs` if they are private +to this library. See ["Header inclusion checking"](#hdrs) for +a more detailed description. + +`.so`, `.lo`, and `.a` files are +pre-compiled files. Your library might have these as +`srcs` if it uses third-party code for which we don't +have source code. + +If the `srcs` attribute includes the label of another rule, +`cc_library` will use the output files of that rule as source files to +compile. This is useful for one-off generation of source code (for more than occasional +use, it's better to implement a Starlark rule class and use the `cc_common` +API) + +Permitted `srcs` file types: + +- C and C++ source files: `.c`, `.cc`, `.cpp`, + `.cxx`, `.c++`, `.C` +- C and C++ header files: `.h`, `.hh`, `.hpp`, + `.hxx`, `.inc`, `.inl`, `.H` +- Assembler with C preprocessor: `.S` +- Archive: `.a`, `.pic.a` +- "Always link" library: `.lo`, `.pic.lo` +- Shared library, versioned or unversioned: `.so`, + `.so.version` +- Object file: `.o`, `.pic.o` + +... and any rules that produce those files (e.g. `cc_embed_data`). +Different extensions denote different programming languages in +accordance with gcc convention. + +`data` + +List of [labels](/concepts/labels); default is `[]` + + The list of files needed by this library at runtime. + +See general comments about `data` +at [Typical attributes defined by\ +most build rules](/reference/be/common-definitions#typical-attributes). + +If a `data` is the name of a generated file, then this +`cc_library` rule automatically depends on the generating +rule. + +If a `data` is a rule name, then this +`cc_library` rule automatically depends on that rule, +and that rule's `outs` are automatically added to +this `cc_library`'s data files. + +Your C++ code can access these data files like so: + +```lang-starlark + + const std::string path = devtools_build::GetDataDependencyFilepath( + "my/test/data/file"); + +``` + +`additional_linker_inputs` + +List of [labels](/concepts/labels); default is `[]` + + Pass these files to the C++ linker command. + +For example, compiled Windows .res files can be provided here to be embedded in +the binary target. + +`conlyopts` + +List of strings; default is `[]` + + Add these options to the C compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + `copts` + +List of strings; default is `[]` + + Add these options to the C/C++ compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + +Each string in this attribute is added in the given order to `COPTS` before +compiling the binary target. The flags take effect only for compiling this target, not +its dependencies, so be careful about header files included elsewhere. +All paths should be relative to the workspace, not to the current package. +This attribute should not be needed outside of `third_party`. + +If the package declares the [feature](/reference/be/functions.html#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings +that consist of a single "Make" variable. + +`cxxopts` + +List of strings; default is `[]` + + Add these options to the C++ compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + `defines` + +List of strings; default is `[]` + + List of defines to add to the compile line. +Subject to ["Make" variable](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). +Each string, which must consist of a single Bourne shell token, +is prepended with `-D` and added to the compile command line to this target, +as well as to every rule that depends on it. Be very careful, since this may have +far-reaching effects. When in doubt, add define values to +[`local_defines`](#cc_binary.local_defines) instead. + `distribs` + +List of strings; default is `[]` + +`dynamic_deps` + +List of [labels](/concepts/labels); default is `[]` + + These are other `cc_shared_library` dependencies the current target depends on. + +The `cc_shared_library` implementation will use the list of +`dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the +current target's `dynamic_deps`) to decide which `cc_libraries` in +the transitive `deps` should not be linked in because they are already provided +by a different `cc_shared_library`. + + +`hdrs_check` + +String; default is `""` + + Deprecated, no-op. + `includes` + +List of strings; default is `[]` + + List of include dirs to be added to the compile line. +Subject to ["Make variable"](/reference/be/make-variables) substitution. +Each string is prepended with the package path and passed to the C++ toolchain for +expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system +with typical feature definitions will produce +`-isystem path_to_package/include_entry`. +This should only be used for third-party libraries that +do not conform to the Google style of writing #include statements. +Unlike [COPTS](#cc_binary.copts), these flags are added for this rule +and every rule that depends on it. (Note: not the rules it depends upon!) Be +very careful, since this may have far-reaching effects. When in doubt, add +"-I" flags to [COPTS](#cc_binary.copts) instead. + +The added `include` paths will include generated files as well as +files in the source tree. + +`link_extra_lib` + +[Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:link_extra_lib"` + + Control linking of extra libraries. + +By default, C++ binaries are linked against `//tools/cpp:link_extra_lib`, +which by default depends on the label flag `//tools/cpp:link_extra_libs`. +Without setting the flag, this library is empty by default. Setting the label flag +allows linking optional dependencies, such as overrides for weak symbols, interceptors +for shared library functions, or special runtime libraries (for malloc replacements, +prefer `malloc` or `--custom_malloc`). Setting this attribute to +`None` disables this behaviour. + +`linkopts` + +List of strings; default is `[]` + + Add these flags to the C++ linker command. +Subject to ["Make" variable](make-variables.html) substitution, +[Bourne shell tokenization](common-definitions.html#sh-tokenization) and +[label expansion](common-definitions.html#label-expansion). +Each string in this attribute is added to `LINKOPTS` before +linking the binary target. + +Each element of this list that does not start with `$` or `-` is +assumed to be the label of a target in `deps`. The +list of files generated by that target is appended to the linker +options. An error is reported if the label is invalid, or is +not declared in `deps`. + +`linkshared` + +Boolean; default is `False` + + Create a shared library. +To enable this attribute, include `linkshared=True` in your rule. By default +this option is off. + +The presence of this flag means that linking occurs with the `-shared` flag +to `gcc`, and the resulting shared library is suitable for loading into for +example a Java program. However, for build purposes it will never be linked into the +dependent binary, as it is assumed that shared libraries built with a +[cc\_binary](#cc_binary) rule are only loaded manually by other programs, so +it should not be considered a substitute for the [cc\_library](#cc_library) +rule. For sake of scalability we recommend avoiding this approach altogether and +simply letting `java_library` depend on `cc_library` rules +instead. + +If you specify both `linkopts=['-static']` and `linkshared=True`, +you get a single completely self-contained unit. If you specify both +`linkstatic=True` and `linkshared=True`, you get a single, mostly +self-contained unit. + +`linkstatic` + +Boolean; default is `True` + + For [`cc_binary`](/reference/be/c-cpp.html#cc_binary) and +[`cc_test`](/reference/be/c-cpp.html#cc_test): link the binary in static +mode. For `cc_library.link_static`: see below. + +By default this option is on for `cc_binary` and off for the rest. + +If enabled and this is a binary or test, this option tells the build tool to link in +`.a`'s instead of `.so`'s for user libraries whenever possible. +System libraries such as libc (but _not_ the C/C++ runtime libraries, +see below) are still linked dynamically, as are libraries for which +there is no static library. So the resulting executable will still be dynamically +linked, hence only _mostly_ static. + +There are really three different ways to link an executable: + +- STATIC with fully\_static\_link feature, in which everything is linked statically; + e.g. " `gcc -static foo.o libbar.a libbaz.a -lm`". + + + This mode is enabled by specifying `fully_static_link` in the + [`features`](/reference/be/common-definitions#features) attribute. +- STATIC, in which all user libraries are linked statically (if a static + version is available), but where system libraries (excluding C/C++ runtime libraries) + are linked dynamically, e.g. " `gcc foo.o libfoo.a libbaz.a -lm`". + + + This mode is enabled by specifying `linkstatic=True`. +- DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is + available), e.g. " `gcc foo.o libfoo.so libbaz.so -lm`". + + + This mode is enabled by specifying `linkstatic=False`. + +If the `linkstatic` attribute or `fully_static_link` in +`features` is used outside of `//third_party` +please include a comment near the rule to explain why. + +The `linkstatic` attribute has a different meaning if used on a +[`cc_library()`](/reference/be/c-cpp.html#cc_library) rule. +For a C++ library, `linkstatic=True` indicates that only +static linking is allowed, so no `.so` will be produced. linkstatic=False does +not prevent static libraries from being created. The attribute is meant to control the +creation of dynamic libraries. + +There should be very little code built with `linkstatic=False` in production. +If `linkstatic=False`, then the build tool will create symlinks to +depended-upon shared libraries in the `*.runfiles` area. + +`local_defines` + +List of strings; default is `[]` + + List of defines to add to the compile line. +Subject to ["Make" variable](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). +Each string, which must consist of a single Bourne shell token, +is prepended with `-D` and added to the compile command line for this target, +but not to its dependents. + `malloc` + +[Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:malloc"` + + Override the default dependency on malloc. + +By default, C++ binaries are linked against `//tools/cpp:malloc`, +which is an empty library so the binary ends up using libc malloc. +This label must refer to a `cc_library`. If compilation is for a non-C++ +rule, this option has no effect. The value of this attribute is ignored if +`linkshared=True` is specified. + +`module_interfaces` + +List of [labels](/concepts/labels); default is `[]` + + The list of files are regarded as C++20 Modules Interface. + +C++ Standard has no restriction about module interface file extension + +- Clang use cppm +- GCC can use any source file extension +- MSVC use ixx + +The use is guarded by the flag +`--experimental_cpp_modules`. + +`nocopts` + +String; default is `""` + + Remove matching options from the C++ compilation command. +Subject to ["Make" variable](/reference/be/make-variables) substitution. +The value of this attribute is interpreted as a regular expression. +Any preexisting `COPTS` that match this regular expression +(including values explicitly specified in the rule's [copts](#cc_binary.copts) attribute) +will be removed from `COPTS` for purposes of compiling this rule. +This attribute should not be needed or used +outside of `third_party`. The values are not preprocessed +in any way other than the "Make" variable substitution. + `reexport_deps` + +List of [labels](/concepts/labels); default is `[]` + +`stamp` + +Integer; default is `-1` + + Whether to encode build information into the binary. Possible values: + +- `stamp = 1`: Always stamp the build information into the binary, even in + [`--nostamp`](/docs/user-manual#flag--stamp) builds. **This** + **setting should be avoided**, since it potentially kills remote caching for the + binary and any downstream actions that depend on it. + +- `stamp = 0`: Always replace build information by constant values. This + gives good build result caching. + +- `stamp = -1`: Embedding of build information is controlled by the + [`--[no]stamp`](/docs/user-manual#flag--stamp) flag. + + +Stamped binaries are _not_ rebuilt unless their dependencies change. + +`win_def_file` + +[Label](/concepts/labels); default is `None` + + The Windows DEF file to be passed to linker. + +This attribute should only be used when Windows is the target platform. +It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. + +## cc\_import + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl) + +``` +cc_import(name, deps, data, hdrs, alwayslink, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, includes, interface_library, linkopts, objects, package_metadata, pic_objects, pic_static_library, restricted_to, shared_library, static_library, strip_include_prefix, system_provided, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +`cc_import` rules allows users to import precompiled C/C++ libraries. + +The following are the typical use cases: + +1\. Linking a static library + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + static_library = "libmylib.a", + # If alwayslink is turned on, + # libmylib.a will be forcely linked into any binary that depends on it. + # alwayslink = 1, +) + +``` + +2\. Linking a shared library (Unix) + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + shared_library = "libmylib.so", +) + +``` + +3\. Linking a shared library with interface library + +On Unix: + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + # libmylib.ifso is an interface library for libmylib.so which will be passed to linker + interface_library = "libmylib.ifso", + # libmylib.so will be available for runtime + shared_library = "libmylib.so", +) + +``` + +On Windows: + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + # mylib.lib is an import library for mylib.dll which will be passed to linker + interface_library = "mylib.lib", + # mylib.dll will be available for runtime + shared_library = "mylib.dll", +) + +``` + +4\. Linking a shared library with `system_provided=True` + +On Unix: + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + interface_library = "libmylib.ifso", # Or we can also use libmylib.so as its own interface library + # libmylib.so is provided by system environment, for example it can be found in LD_LIBRARY_PATH. + # This indicates that Bazel is not responsible for making libmylib.so available. + system_provided = 1, +) + +``` + +On Windows: + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + # mylib.lib is an import library for mylib.dll which will be passed to linker + interface_library = "mylib.lib", + # mylib.dll is provided by system environment, for example it can be found in PATH. + # This indicates that Bazel is not responsible for making mylib.dll available. + system_provided = 1, +) + +``` + +5\. Linking to static or shared library + +On Unix: + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + static_library = "libmylib.a", + shared_library = "libmylib.so", +) + +``` + +On Windows: + +```lang-starlark + +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + static_library = "libmylib.lib", # A normal static library + interface_library = "mylib.lib", # An import library for mylib.dll + shared_library = "mylib.dll", +) + +``` + +The remaining is the same on Unix and Windows: + +```lang-starlark + +# first will link to libmylib.a (or libmylib.lib) +cc_binary( + name = "first", + srcs = ["first.cc"], + deps = [":mylib"], + linkstatic = 1, # default value +) + +# second will link to libmylib.so (or libmylib.lib) +cc_binary( + name = "second", + srcs = ["second.cc"], + deps = [":mylib"], + linkstatic = 0, +) + +``` + +`cc_import` supports an include attribute. For example: + +```lang-starlark + +cc_import( + name = "curl_lib", + hdrs = glob(["vendor/curl/include/curl/*.h"]), + includes = ["vendor/curl/include"], + shared_library = "vendor/curl/lib/.libs/libcurl.dylib", +) + +``` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + + The list of other libraries that the target depends upon. +See general comments about `deps` +at [Typical attributes defined by\ +most build rules](/reference/be/common-definitions#typical-attributes). + `hdrs` + +List of [labels](/concepts/labels); default is `[]` + + The list of header files published by +this precompiled library to be directly included by sources in dependent rules. + `alwayslink` + +Boolean; default is `False` + + If 1, any binary that depends (directly or indirectly) on this C++ +precompiled library will link in all the object files archived in the static library, +even if some contain no symbols referenced by the binary. +This is useful if your code isn't explicitly called by code in +the binary, e.g., if your code registers to receive some callback +provided by some service. + +If alwayslink doesn't work with VS 2017 on Windows, that is due to a +[known issue](https://github.com/bazelbuild/bazel/issues/3949), +please upgrade your VS 2017 to the latest version. + +`includes` + +List of strings; default is `[]` + + List of include dirs to be added to the compile line. +Subject to ["Make variable"](/reference/be/make-variables) substitution. +Each string is prepended with the package path and passed to the C++ toolchain for +expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system +with typical feature definitions will produce +`-isystem path_to_package/include_entry`. +This should only be used for third-party libraries that +do not conform to the Google style of writing #include statements. +Unlike [COPTS](#cc_binary.copts), these flags are added for this rule +and every rule that depends on it. (Note: not the rules it depends upon!) Be +very careful, since this may have far-reaching effects. When in doubt, add +"-I" flags to [COPTS](#cc_binary.copts) instead. + +The default `include` path doesn't include generated +files. If you need to `#include` a generated header +file, list it in the `srcs`. + +`interface_library` + +[Label](/concepts/labels); default is `None` + + A single interface library for linking the shared library. + +Permitted file types: +`.ifso`, +`.tbd`, +`.lib`, +`.so` +or `.dylib` + +`linkopts` + +List of strings; default is `[]` + + Add these flags to the C++ linker command. +Subject to ["Make" variable](make-variables.html) substitution, +[Bourne shell tokenization](common-definitions.html#sh-tokenization) and +[label expansion](common-definitions.html#label-expansion). +Each string in this attribute is added to `LINKOPTS` before +linking the binary target. + +Each element of this list that does not start with `$` or `-` is +assumed to be the label of a target in `deps`. The +list of files generated by that target is appended to the linker +options. An error is reported if the label is invalid, or is +not declared in `deps`. + +`objects` + +List of [labels](/concepts/labels); default is `[]` + +`pic_objects` + +List of [labels](/concepts/labels); default is `[]` + +`pic_static_library` + +[Label](/concepts/labels); default is `None` + +`shared_library` + +[Label](/concepts/labels); default is `None` + + A single precompiled shared library. Bazel ensures it is available to the +binary that depends on it during runtime. + +Permitted file types: +`.so`, +`.dll` +or `.dylib` + +`static_library` + +[Label](/concepts/labels); default is `None` + + A single precompiled static library. + +Permitted file types: +`.a`, +`.pic.a` +or `.lib` + +`strip_include_prefix` + +String; default is `""` + + The prefix to strip from the paths of the headers of this rule. + +When set, the headers in the `hdrs` attribute of this rule are accessible +at their path with this prefix cut off. + +If it's a relative path, it's taken as a package-relative one. If it's an absolute one, +it's understood as a repository-relative path. + +The prefix in the `include_prefix` attribute is added after this prefix is +stripped. + +This attribute is only legal under `third_party`. + + +`system_provided` + +Boolean; default is `False` + + If 1, it indicates the shared library required at runtime is provided by the system. In +this case, `interface_library` should be specified and +`shared_library` should be empty. + + +## cc\_library + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_library.bzl) + +``` +cc_library(name, deps, srcs, data, hdrs, additional_compiler_inputs, additional_linker_inputs, alwayslink, aspect_hints, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, hdrs_check, implementation_deps, include_prefix, includes, licenses, linkopts, linkstamp, linkstatic, local_defines, module_interfaces, package_metadata, restricted_to, strip_include_prefix, tags, target_compatible_with, testonly, textual_hdrs, toolchains, visibility, win_def_file) +``` + +Use `cc_library()` for C++-compiled libraries. +The result is either a `.so`, `.lo`, +or `.a`, depending on what is needed. + +If you build something with static linking that depends on +a `cc_library`, the output of a depended-on library rule +is the `.a` file. If you specify +`alwayslink=True`, you get the `.lo` file. + +The actual output file name is `libfoo.so` for +the shared library, where _foo_ is the name of the rule. The +other kinds of libraries end with `.lo` and `.a`, +respectively. If you need a specific shared library name, for +example, to define a Python module, use a genrule to copy the library +to the desired name. + +#### Header inclusion checking + +All header files that are used in the build must be declared in +the `hdrs` or `srcs` of `cc_*` rules. +This is enforced. + +For `cc_library` rules, headers in `hdrs` comprise the +public interface of the library and can be directly included both +from the files in `hdrs` and `srcs` of the library +itself as well as from files in `hdrs` and `srcs` +of `cc_*` rules that list the library in their `deps`. +Headers in `srcs` must only be directly included from the files +in `hdrs` and `srcs` of the library itself. When +deciding whether to put a header into `hdrs` or `srcs`, +you should ask whether you want consumers of this library to be able to +directly include it. This is roughly the same decision as +between `public` and `private` visibility in programming languages. + +`cc_binary` and `cc_test` rules do not have an exported +interface, so they also do not have a `hdrs` attribute. All headers +that belong to the binary or test directly should be listed in +the `srcs`. + +To illustrate these rules, look at the following example. + +```lang-starlark + +cc_binary( + name = "foo", + srcs = [ + "foo.cc", + "foo.h", + ], + deps = [":bar"], +) + +cc_library( + name = "bar", + srcs = [ + "bar.cc", + "bar-impl.h", + ], + hdrs = ["bar.h"], + deps = [":baz"], +) + +cc_library( + name = "baz", + srcs = [ + "baz.cc", + "baz-impl.h", + ], + hdrs = ["baz.h"], +) + +``` + +The allowed direct inclusions in this example are listed in the table below. +For example `foo.cc` is allowed to directly +include `foo.h` and `bar.h`, but not `baz.h`. + +Including fileAllowed inclusionsfoo.hbar.hfoo.ccfoo.h bar.hbar.hbar-impl.h baz.hbar-impl.hbar.h baz.hbar.ccbar.h bar-impl.h baz.hbaz.hbaz-impl.hbaz-impl.hbaz.hbaz.ccbaz.h baz-impl.h + +The inclusion checking rules only apply to _direct_ +inclusions. In the example above `foo.cc` is allowed to +include `bar.h`, which may include `baz.h`, which in +turn is allowed to include `baz-impl.h`. Technically, the +compilation of a `.cc` file may transitively include any header +file in the `hdrs` or `srcs` in +any `cc_library` in the transitive `deps` closure. In +this case the compiler may read `baz.h` and `baz-impl.h` +when compiling `foo.cc`, but `foo.cc` must not +contain `#include "baz.h"`. For that to be +allowed, `baz` must be added to the `deps` +of `foo`. + +Bazel depends on toolchain support to enforce the inclusion checking rules. +The `layering_check` feature has to be supported by the toolchain +and requested explicitly, for example via the +`--features=layering_check` command-line flag or the +`features` parameter of the +[`package`](/reference/be/functions.html#package) function. The toolchains +provided by Bazel only support this feature with clang on Unix and macOS. + +#### Examples + +We use the `alwayslink` flag to force the linker to link in +this code although the main binary code doesn't reference it. + +```lang-starlark + +cc_library( + name = "ast_inspector_lib", + srcs = ["ast_inspector_lib.cc"], + hdrs = ["ast_inspector_lib.h"], + visibility = ["//visibility:public"], + deps = ["//third_party/llvm/llvm/tools/clang:frontend"], + # alwayslink as we want to be able to call things in this library at + # debug time, even if they aren't used anywhere in the code. + alwayslink = 1, +) + +``` + +The following example comes from +`third_party/python2_4_3/BUILD`. +Some of the code uses the `dl` library (to load +another, dynamic library), so this +rule specifies the `-ldl` link option to link the +`dl` library. + +```lang-starlark + +cc_library( + name = "python2_4_3", + linkopts = [ + "-ldl", + "-lutil", + ], + deps = ["//third_party/expat"], +) + +``` + +The following example comes from `third_party/kde/BUILD`. +We keep pre-built `.so` files in the depot. +The header files live in a subdirectory named `include`. + +```lang-starlark + +cc_library( + name = "kde", + srcs = [ + "lib/libDCOP.so", + "lib/libkdesu.so", + "lib/libkhtml.so", + "lib/libkparts.so", + ...more .so files..., + ], + includes = ["include"], + deps = ["//third_party/X11"], +) + +``` + +The following example comes from `third_party/gles/BUILD`. +Third-party code often needs some `defines` and +`linkopts`. + +```lang-starlark + +cc_library( + name = "gles", + srcs = [ + "GLES/egl.h", + "GLES/gl.h", + "ddx.c", + "egl.c", + ], + defines = [ + "USE_FLOAT", + "__GL_FLOAT", + "__GL_COMMON", + ], + linkopts = ["-ldl"], # uses dlopen(), dl library + deps = [ + "es", + "//third_party/X11", + ], +) + +``` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + + The list of other libraries that the library target depends upon. + +These can be `cc_library` or `objc_library` targets. + +See general comments about `deps` +at [Typical attributes defined by\ +most build rules](/reference/be/common-definitions#typical-attributes). + +These should be names of C++ library rules. +When you build a binary that links this rule's library, +you will also link the libraries in `deps`. + +Despite the "deps" name, not all of this library's clients +belong here. Run-time data dependencies belong in `data`. +Source files generated by other rules belong in `srcs`. + +To link in a pre-compiled third-party library, add its name to +the `srcs` instead. + +To depend on something without linking it to this library, add its +name to the `data` instead. + +`srcs` + +List of [labels](/concepts/labels); default is `[]` + + The list of C and C++ files that are processed to create the library target. +These are C/C++ source and header files, either non-generated (normal source +code) or generated. + +All `.cc`, `.c`, and `.cpp` files will +be compiled. These might be generated files: if a named file is in +the `outs` of some other rule, this `cc_library` +will automatically depend on that other rule. + +Pure assembler files (.s, .asm) are not preprocessed and are typically built using +the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built +using the C/C++ compiler. + +A `.h` file will not be compiled, but will be available for +inclusion by sources in this rule. Both `.cc` and +`.h` files can directly include headers listed in +these `srcs` or in the `hdrs` of this rule or any +rule listed in the `deps` argument. + +All `#include` d files must be mentioned in the +`hdrs` attribute of this or referenced `cc_library` +rules, or they should be listed in `srcs` if they are private +to this library. See ["Header inclusion checking"](#hdrs) for +a more detailed description. + +`.so`, `.lo`, and `.a` files are +pre-compiled files. Your library might have these as +`srcs` if it uses third-party code for which we don't +have source code. + +If the `srcs` attribute includes the label of another rule, +`cc_library` will use the output files of that rule as source files to +compile. This is useful for one-off generation of source code (for more than occasional +use, it's better to implement a Starlark rule class and use the `cc_common` +API) + +Permitted `srcs` file types: + +- C and C++ source files: `.c`, `.cc`, `.cpp`, + `.cxx`, `.c++`, `.C` +- C and C++ header files: `.h`, `.hh`, `.hpp`, + `.hxx`, `.inc`, `.inl`, `.H` +- Assembler with C preprocessor: `.S` +- Archive: `.a`, `.pic.a` +- "Always link" library: `.lo`, `.pic.lo` +- Shared library, versioned or unversioned: `.so`, + `.so.version` +- Object file: `.o`, `.pic.o` + +... and any rules that produce those files (e.g. `cc_embed_data`). +Different extensions denote different programming languages in +accordance with gcc convention. + +`data` + +List of [labels](/concepts/labels); default is `[]` + + The list of files needed by this library at runtime. + +See general comments about `data` +at [Typical attributes defined by\ +most build rules](/reference/be/common-definitions#typical-attributes). + +If a `data` is the name of a generated file, then this +`cc_library` rule automatically depends on the generating +rule. + +If a `data` is a rule name, then this +`cc_library` rule automatically depends on that rule, +and that rule's `outs` are automatically added to +this `cc_library`'s data files. + +Your C++ code can access these data files like so: + +```lang-starlark + + const std::string path = devtools_build::GetDataDependencyFilepath( + "my/test/data/file"); + +``` + +`hdrs` + +List of [labels](/concepts/labels); default is `[]` + + The list of header files published by +this library to be directly included by sources in dependent rules. + +This is the strongly preferred location for declaring header files that +describe the interface for the library. These headers will be made +available for inclusion by sources in this rule or in dependent rules. +Headers not meant to be included by a client of this library should be +listed in the `srcs` attribute instead, even if they are +included by a published header. See ["Header inclusion\ +checking"](#hdrs) for a more detailed description. + +Permitted `headers` file types: +`.h`, +`.hh`, +`.hpp`, +`.hxx`. + +`additional_compiler_inputs` + +List of [labels](/concepts/labels); default is `[]` + + Any additional files you might want to pass to the compiler command line, such as sanitizer +ignorelists, for example. Files specified here can then be used in copts with the +$(location) function. + `additional_linker_inputs` + +List of [labels](/concepts/labels); default is `[]` + + Pass these files to the C++ linker command. + +For example, compiled Windows .res files can be provided here to be embedded in +the binary target. + +`alwayslink` + +Boolean; default is `False` + + If 1, any binary that depends (directly or indirectly) on this C++ +library will link in all the object files for the files listed in +`srcs`, even if some contain no symbols referenced by the binary. +This is useful if your code isn't explicitly called by code in +the binary, e.g., if your code registers to receive some callback +provided by some service. + +If alwayslink doesn't work with VS 2017 on Windows, that is due to a +[known issue](https://github.com/bazelbuild/bazel/issues/3949), +please upgrade your VS 2017 to the latest version. + +`conlyopts` + +List of strings; default is `[]` + + Add these options to the C compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + `copts` + +List of strings; default is `[]` + + Add these options to the C/C++ compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + +Each string in this attribute is added in the given order to `COPTS` before +compiling the binary target. The flags take effect only for compiling this target, not +its dependencies, so be careful about header files included elsewhere. +All paths should be relative to the workspace, not to the current package. +This attribute should not be needed outside of `third_party`. + +If the package declares the [feature](/reference/be/functions.html#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings +that consist of a single "Make" variable. + +`cxxopts` + +List of strings; default is `[]` + + Add these options to the C++ compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + `defines` + +List of strings; default is `[]` + + List of defines to add to the compile line. +Subject to ["Make" variable](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). +Each string, which must consist of a single Bourne shell token, +is prepended with `-D` and added to the compile command line to this target, +as well as to every rule that depends on it. Be very careful, since this may have +far-reaching effects. When in doubt, add define values to +[`local_defines`](#cc_binary.local_defines) instead. + `hdrs_check` + +String; default is `""` + + Deprecated, no-op. + `implementation_deps` + +List of [labels](/concepts/labels); default is `[]` + + The list of other libraries that the library target depends on. Unlike with +`deps`, the headers and include paths of these libraries (and all their +transitive deps) are only used for compilation of this library, and not libraries that +depend on it. Libraries specified with `implementation_deps` are still linked in +binary targets that depend on this library. + `include_prefix` + +String; default is `""` + + The prefix to add to the paths of the headers of this rule. + +When set, the headers in the `hdrs` attribute of this rule are accessible +at is the value of this attribute prepended to their repository-relative path. + +The prefix in the `strip_include_prefix` attribute is removed before this +prefix is added. + +This attribute is only legal under `third_party`. + + +`includes` + +List of strings; default is `[]` + + List of include dirs to be added to the compile line. +Subject to ["Make variable"](/reference/be/make-variables) substitution. +Each string is prepended with the package path and passed to the C++ toolchain for +expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system +with typical feature definitions will produce +`-isystem path_to_package/include_entry`. +This should only be used for third-party libraries that +do not conform to the Google style of writing #include statements. +Unlike [COPTS](#cc_binary.copts), these flags are added for this rule +and every rule that depends on it. (Note: not the rules it depends upon!) Be +very careful, since this may have far-reaching effects. When in doubt, add +"-I" flags to [COPTS](#cc_binary.copts) instead. + +The added `include` paths will include generated files as well as +files in the source tree. + +`linkopts` + +List of strings; default is `[]` + + See [`cc_binary.linkopts`](/reference/be/c-cpp.html#cc_binary.linkopts). +The `linkopts` attribute is also applied to any target that +depends, directly or indirectly, on this library via `deps` +attributes (or via other attributes that are treated similarly: +the [`malloc`](/reference/be/c-cpp.html#cc_binary.malloc) +attribute of [`cc_binary`](/reference/be/c-cpp.html#cc_binary)). Dependency +linkopts take precedence over dependent linkopts (i.e. dependency linkopts +appear later in the command line). Linkopts specified in +[`--linkopt`](../user-manual.html#flag--linkopt) +take precedence over rule linkopts. + +Note that the `linkopts` attribute only applies +when creating `.so` files or executables, not +when creating `.a` or `.lo` files. +So if the `linkstatic=True` attribute is set, the +`linkopts` attribute has no effect on the creation of +this library, only on other targets which depend on this library. + +Also, it is important to note that "-Wl,-soname" or "-Xlinker -soname" +options are not supported and should never be specified in this attribute. + +The `.so` files produced by `cc_library` +rules are not linked against the libraries that they depend +on. If you're trying to create a shared library for use +outside of the main repository, e.g. for manual use +with `dlopen()` or `LD_PRELOAD`, +it may be better to use a `cc_binary` rule +with the `linkshared=True` attribute. +See [`cc_binary.linkshared`](/reference/be/c-cpp.html#cc_binary.linkshared). + +`linkstamp` + +[Label](/concepts/labels); default is `None` + + Simultaneously compiles and links the specified C++ source file into the final +binary. This trickery is required to introduce timestamp +information into binaries; if we compiled the source file to an +object file in the usual way, the timestamp would be incorrect. +A linkstamp compilation may not include any particular set of +compiler flags and so should not depend on any particular +header, compiler option, or other build variable. +_This option should only be needed in the_ +_`base` package._`linkstatic` + +Boolean; default is `False` + + For [`cc_binary`](/reference/be/c-cpp.html#cc_binary) and +[`cc_test`](/reference/be/c-cpp.html#cc_test): link the binary in static +mode. For `cc_library.link_static`: see below. + +By default this option is on for `cc_binary` and off for the rest. + +If enabled and this is a binary or test, this option tells the build tool to link in +`.a`'s instead of `.so`'s for user libraries whenever possible. +System libraries such as libc (but _not_ the C/C++ runtime libraries, +see below) are still linked dynamically, as are libraries for which +there is no static library. So the resulting executable will still be dynamically +linked, hence only _mostly_ static. + +There are really three different ways to link an executable: + +- STATIC with fully\_static\_link feature, in which everything is linked statically; + e.g. " `gcc -static foo.o libbar.a libbaz.a -lm`". + + + This mode is enabled by specifying `fully_static_link` in the + [`features`](/reference/be/common-definitions#features) attribute. +- STATIC, in which all user libraries are linked statically (if a static + version is available), but where system libraries (excluding C/C++ runtime libraries) + are linked dynamically, e.g. " `gcc foo.o libfoo.a libbaz.a -lm`". + + + This mode is enabled by specifying `linkstatic=True`. +- DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is + available), e.g. " `gcc foo.o libfoo.so libbaz.so -lm`". + + + This mode is enabled by specifying `linkstatic=False`. + +If the `linkstatic` attribute or `fully_static_link` in +`features` is used outside of `//third_party` +please include a comment near the rule to explain why. + +The `linkstatic` attribute has a different meaning if used on a +[`cc_library()`](/reference/be/c-cpp.html#cc_library) rule. +For a C++ library, `linkstatic=True` indicates that only +static linking is allowed, so no `.so` will be produced. linkstatic=False does +not prevent static libraries from being created. The attribute is meant to control the +creation of dynamic libraries. + +There should be very little code built with `linkstatic=False` in production. +If `linkstatic=False`, then the build tool will create symlinks to +depended-upon shared libraries in the `*.runfiles` area. + +`local_defines` + +List of strings; default is `[]` + + List of defines to add to the compile line. +Subject to ["Make" variable](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). +Each string, which must consist of a single Bourne shell token, +is prepended with `-D` and added to the compile command line for this target, +but not to its dependents. + `module_interfaces` + +List of [labels](/concepts/labels); default is `[]` + + The list of files are regarded as C++20 Modules Interface. + +C++ Standard has no restriction about module interface file extension + +- Clang use cppm +- GCC can use any source file extension +- MSVC use ixx + +The use is guarded by the flag +`--experimental_cpp_modules`. + +`strip_include_prefix` + +String; default is `""` + + The prefix to strip from the paths of the headers of this rule. + +When set, the headers in the `hdrs` attribute of this rule are accessible +at their path with this prefix cut off. + +If it's a relative path, it's taken as a package-relative one. If it's an absolute one, +it's understood as a repository-relative path. + +The prefix in the `include_prefix` attribute is added after this prefix is +stripped. + +This attribute is only legal under `third_party`. + + +`textual_hdrs` + +List of [labels](/concepts/labels); default is `[]` + + The list of header files published by +this library to be textually included by sources in dependent rules. + +This is the location for declaring header files that cannot be compiled on their own; +that is, they always need to be textually included by other source files to build valid +code. + +`win_def_file` + +[Label](/concepts/labels); default is `None` + + The Windows DEF file to be passed to linker. + +This attribute should only be used when Windows is the target platform. +It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. + +## cc\_shared\_library + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_shared_library.bzl) + +``` +cc_shared_library(name, deps, additional_linker_inputs, aspect_hints, compatible_with, deprecation, dynamic_deps, exec_compatible_with, exec_group_compatible_with, exec_properties, experimental_disable_topo_sort_do_not_use_remove_before_7_0, exports_filter, features, package_metadata, restricted_to, roots, shared_lib_name, static_deps, tags, target_compatible_with, testonly, toolchains, user_link_flags, visibility, win_def_file) +``` + +It produces a shared library. + +#### Example + +``` +cc_shared_library( + name = "foo_shared", + deps = [ + ":foo", + ], + dynamic_deps = [ + ":bar_shared", + ], + additional_linker_inputs = [ + ":foo.lds", + ], + user_link_flags = [ + "-Wl,--version-script=$(location :foo.lds)", + ], +) +cc_library( + name = "foo", + srcs = ["foo.cc"], + hdrs = ["foo.h"], + deps = [ + ":bar", + ":baz", + ], +) +cc_shared_library( + name = "bar_shared", + shared_lib_name = "bar.so", + deps = [":bar"], +) +cc_library( + name = "bar", + srcs = ["bar.cc"], + hdrs = ["bar.h"], +) +cc_library( + name = "baz", + srcs = ["baz.cc"], + hdrs = ["baz.h"], +) + +``` + +In the example `foo_shared` statically links `foo` +and `baz`, the latter being a transitive dependency. It doesn't +link `bar` because it is already provided dynamically by the +`dynamic_dep` `bar_shared`. + +`foo_shared` uses a linker script \*.lds file to control which +symbols should be exported. The `cc_shared_library` rule logic does +not control which symbols get exported, it only uses what is assumed to be +exported to give errors during analysis phase if two shared libraries export the +same targets. + +Every direct dependency of `cc_shared_library` is assumed to be +exported. Therefore, Bazel assumes during analysis that `foo` is being +exported by `foo_shared`. `baz` is not assumed to be exported +by `foo_shared`. Every target matched by the `exports_filter` +is also assumed to be exported. + +Every single `cc_library` in the example should appear at most in one +`cc_shared_library`. If we wanted to link `baz` also into +`bar_shared` we would need to add +`tags = ["LINKABLE_MORE_THAN_ONCE"]` to `baz`. + +Due to the `shared_lib_name` attribute, the file produced by +`bar_shared` will have the name `bar.so` as opposed +to the name `libbar.so` that it would have by default on Linux. + +#### Errors + +##### `Two shared libraries in dependencies export the same symbols.` + +This will happen whenever you are creating a target with two different +`cc_shared_library` dependencies that export the same target. To fix this +you need to stop the libraries from being exported in one of the +`cc_shared_library` dependencies. + +##### `Two shared libraries in dependencies link the same library statically` + +This will happen whenever you are creating a new `cc_shared_library` with two +different `cc_shared_library` dependencies that link the same target statically. +Similar to the error with exports. + +One way to fix this is to stop linking the library into one of the +`cc_shared_library` dependencies. At the same time, the one that still links it +needs to export the library so that the one not linking it keeps visibility to +the symbols. Another way is to pull out a third library that exports the target. +A third way is to tag the culprit `cc_library` with `LINKABLE_MORE_THAN_ONCE` +but this fix should be rare and you should absolutely make sure that the +`cc_library` is indeed safe to link more than once. + +##### ``'//foo:foo' is already linked statically in '//bar:bar' but not exported` `` + +This means that a library in the transitive closure of your `deps` is reachable +without going through one of the `cc_shared_library` dependencies but is already +linked into a different `cc_shared_library` in `dynamic_deps` and is not +exported. + +The solution is to export it from the `cc_shared_library` dependency or pull out +a third `cc_shared_library` that exports it. + +##### `Do not place libraries which only contain a precompiled dynamic library in deps. ` + +If you have a precompiled dynamic library, this doesn't need to and cannot be +linked statically into the current `cc_shared_library` target that you are +currently creating. Therefore, it doesn't belong in `deps` of the +`cc_shared_library`. If this precompiled dynamic library is a dependency of one +of your `cc_libraries`, then the `cc_library` needs to depend on it +directly. + +##### `Trying to export a library already exported by a different shared library` + +You will see this error if on the current rule you are claiming to export a +target that is already being exported by one of your dynamic dependencies. + +To fix this, remove the target from `deps` and just rely on it from the dynamic +dependency or make sure that the `exports_filter` doesn't catch this target. + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + + Top level libraries that will unconditionally be statically linked into the shared library +after being whole-archived. + +Any transitive library dependency of these direct deps will be linked into this shared +library as long as they have not already been linked by a `cc_shared_library` +in `dynamic_deps`. + +During analysis, the rule implementation will consider any target listed in +`deps` as being exported by the shared library in order to give errors when +multiple `cc_shared_libraries` export the same targets. The rule implementation +does not take care of informing the linker about which symbols should be exported by the +shared object. The user should take care of this via linker scripts or visibility +declarations in the source code. + +The implementation will also trigger errors whenever the same library is linked statically +into more than one `cc_shared_library`. This can be avoided by adding +`"LINKABLE_MORE_THAN_ONCE"` to the `cc_library.tags` or by listing +the \`cc\_library\` as an export of one of the shared libraries so that one can be made a +`dynamic_dep` of the other. + +`additional_linker_inputs` + +List of [labels](/concepts/labels); default is `[]` + + Any additional files that you may want to pass to the linker, for example, linker scripts. +You have to separately pass any linker flags that the linker needs in order to be aware +of this file. You can do so via the `user_link_flags` attribute. + `dynamic_deps` + +List of [labels](/concepts/labels); default is `[]` + + These are other `cc_shared_library` dependencies the current target depends on. + +The `cc_shared_library` implementation will use the list of +`dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the +current target's `dynamic_deps`) to decide which `cc_libraries` in +the transitive `deps` should not be linked in because they are already provided +by a different `cc_shared_library`. + +`experimental_disable_topo_sort_do_not_use_remove_before_7_0` + +Boolean; default is `False` + +`exports_filter` + +List of strings; default is `[]` + + This attribute contains a list of targets that are claimed to be exported by the current +shared library. + +Any target `deps` is already understood to be exported by the shared library. +This attribute should be used to list any targets that are exported by the shared library +but are transitive dependencies of `deps`. + +Note that this attribute is not actually adding a dependency edge to those targets, the +dependency edge should instead be created by `deps`.The entries in this +attribute are just strings. Keep in mind that when placing a target in this attribute, +this is considered a claim that the shared library exports the symbols from that target. +The `cc_shared_library` logic doesn't actually handle telling the linker which +symbols should be exported. + +The following syntax is allowed: + +`//foo:__pkg__` to account for any target in foo/BUILD + +`//foo:__subpackages__` to account for any target in foo/BUILD or any other +package below foo/ like foo/bar/BUILD + +`roots` + +List of [labels](/concepts/labels); default is `[]` + +`shared_lib_name` + +String; default is `""` + + By default cc\_shared\_library will use a name for the shared library output file based on +the target's name and the platform. This includes an extension and sometimes a prefix. +Sometimes you may not want the default name, for example, when loading C++ shared libraries +for Python the default lib\* prefix is often not desired, in which case you can use this +attribute to choose a custom name. + `static_deps` + +List of strings; default is `[]` + +`user_link_flags` + +List of strings; default is `[]` + + Any additional flags that you may want to pass to the linker. For example, to make the +linker aware of a linker script passed via additional\_linker\_inputs you can use the +following: + +```lang-starlark + + cc_shared_library( + name = "foo_shared", + additional_linker_inputs = select({ + "//src/conditions:linux": [ + ":foo.lds", + ":additional_script.txt", + ], + "//conditions:default": []}), + user_link_flags = select({ + "//src/conditions:linux": [ + "-Wl,-rpath,kittens", + "-Wl,--version-script=$(location :foo.lds)", + "-Wl,--script=$(location :additional_script.txt)", + ], + "//conditions:default": []}), + ... + ) + +``` + +`win_def_file` + +[Label](/concepts/labels); default is `None` + + The Windows DEF file to be passed to linker. + +This attribute should only be used when Windows is the target platform. +It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. + +## cc\_static\_library + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_static_library.bzl) + +``` +cc_static_library(name, deps, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, package_metadata, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + + Produces a static library from a list of targets and their transitive dependencies. + +The resulting static library contains the object files of the targets listed in +`deps` as well as their transitive dependencies, with preference given to +`PIC` objects. + +#### Output groups + +##### `linkdeps` + +A text file containing the labels of those transitive dependencies of targets listed in +`deps` that did not contribute any object files to the static library, but do +provide at least one static, dynamic or interface library. The resulting static library +may require these libraries to be available at link time. + +##### `linkopts` + +A text file containing the user-provided `linkopts` of all transitive +dependencies of targets listed in `deps`. + +#### Duplicate symbols + +By default, the `cc_static_library` rule checks that the resulting static +library does not contain any duplicate symbols. If it does, the build fails with an error +message that lists the duplicate symbols and the object files containing them. + +This check can be disabled per target or per package by setting +`features = ["-symbol_check"]` or globally via +`--features=-symbol_check`. + +##### Toolchain support for `symbol_check` + +The auto-configured C++ toolchains shipped with Bazel support the +`symbol_check` feature on all platforms. Custom toolchains can add support for +it in one of two ways: + +- Implementing the `ACTION_NAMES.validate_static_library` action and + enabling it with the `symbol_check` feature. The tool set in the action is + invoked with two arguments, the static library to check for duplicate symbols and the + path of a file that must be created if the check passes. +- Having the `symbol_check` feature add archiver flags that cause the + action creating the static library to fail on duplicate symbols. + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + + The list of targets to combine into a static library, including all their transitive +dependencies. + +Dependencies that do not provide any object files are not included in the static +library, but their labels are collected in the file provided by the +`linkdeps` output group. + +## cc\_test + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_test.bzl) + +``` +cc_test(name, deps, srcs, data, additional_linker_inputs, args, aspect_hints, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, distribs, dynamic_deps, env, env_inherit, exec_compatible_with, exec_group_compatible_with, exec_properties, features, flaky, hdrs_check, includes, licenses, link_extra_lib, linkopts, linkshared, linkstatic, local, local_defines, malloc, module_interfaces, nocopts, package_metadata, reexport_deps, restricted_to, shard_count, size, stamp, tags, target_compatible_with, testonly, timeout, toolchains, visibility, win_def_file) +``` + +A `cc_test()` rule compiles a test. Here, a test +is a binary wrapper around some testing code. + +_By default, C++ tests are dynamically linked._ + +To statically link a unit test, specify +[`linkstatic=True`](/reference/be/c-cpp.html#cc_binary.linkstatic). +It would probably be good to comment why your test needs +`linkstatic`; this is probably not obvious. + +#### Implicit output targets + +- `name.stripped` (only built if explicitly requested): A stripped + version of the binary. `strip -g` is run on the binary to remove debug + symbols. Additional strip options can be provided on the command line using + `--stripopt=-foo`. +- `name.dwp` (only built if explicitly requested): If + [Fission](https://gcc.gnu.org/wiki/DebugFission) is enabled: a debug + information package file suitable for debugging remotely deployed binaries. Else: an + empty file. + +See the [cc\_binary()](/reference/be/c-cpp.html#cc_binary_args) arguments, except that +the `stamp` argument is set to 0 by default for tests and +that `cc_test` has extra [attributes common to all test rules (\*\_test)](/reference/be/common-definitions#common-attributes-tests). + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + + The list of other libraries to be linked in to the binary target. + +These can be `cc_library` or `objc_library` +targets. + +It is also allowed to +put linker scripts (.lds) into deps, and reference them in +[linkopts](#cc_binary.linkopts). + `srcs` + +List of [labels](/concepts/labels); default is `[]` + + The list of C and C++ files that are processed to create the library target. +These are C/C++ source and header files, either non-generated (normal source +code) or generated. + +All `.cc`, `.c`, and `.cpp` files will +be compiled. These might be generated files: if a named file is in +the `outs` of some other rule, this `cc_library` +will automatically depend on that other rule. + +Pure assembler files (.s, .asm) are not preprocessed and are typically built using +the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built +using the C/C++ compiler. + +A `.h` file will not be compiled, but will be available for +inclusion by sources in this rule. Both `.cc` and +`.h` files can directly include headers listed in +these `srcs` or in the `hdrs` of this rule or any +rule listed in the `deps` argument. + +All `#include` d files must be mentioned in the +`hdrs` attribute of this or referenced `cc_library` +rules, or they should be listed in `srcs` if they are private +to this library. See ["Header inclusion checking"](#hdrs) for +a more detailed description. + +`.so`, `.lo`, and `.a` files are +pre-compiled files. Your library might have these as +`srcs` if it uses third-party code for which we don't +have source code. + +If the `srcs` attribute includes the label of another rule, +`cc_library` will use the output files of that rule as source files to +compile. This is useful for one-off generation of source code (for more than occasional +use, it's better to implement a Starlark rule class and use the `cc_common` +API) + +Permitted `srcs` file types: + +- C and C++ source files: `.c`, `.cc`, `.cpp`, + `.cxx`, `.c++`, `.C` +- C and C++ header files: `.h`, `.hh`, `.hpp`, + `.hxx`, `.inc`, `.inl`, `.H` +- Assembler with C preprocessor: `.S` +- Archive: `.a`, `.pic.a` +- "Always link" library: `.lo`, `.pic.lo` +- Shared library, versioned or unversioned: `.so`, + `.so.version` +- Object file: `.o`, `.pic.o` + +... and any rules that produce those files (e.g. `cc_embed_data`). +Different extensions denote different programming languages in +accordance with gcc convention. + +`data` + +List of [labels](/concepts/labels); default is `[]` + + The list of files needed by this library at runtime. + +See general comments about `data` +at [Typical attributes defined by\ +most build rules](/reference/be/common-definitions#typical-attributes). + +If a `data` is the name of a generated file, then this +`cc_library` rule automatically depends on the generating +rule. + +If a `data` is a rule name, then this +`cc_library` rule automatically depends on that rule, +and that rule's `outs` are automatically added to +this `cc_library`'s data files. + +Your C++ code can access these data files like so: + +```lang-starlark + + const std::string path = devtools_build::GetDataDependencyFilepath( + "my/test/data/file"); + +``` + +`additional_linker_inputs` + +List of [labels](/concepts/labels); default is `[]` + + Pass these files to the C++ linker command. + +For example, compiled Windows .res files can be provided here to be embedded in +the binary target. + +`conlyopts` + +List of strings; default is `[]` + + Add these options to the C compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + `copts` + +List of strings; default is `[]` + + Add these options to the C/C++ compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + +Each string in this attribute is added in the given order to `COPTS` before +compiling the binary target. The flags take effect only for compiling this target, not +its dependencies, so be careful about header files included elsewhere. +All paths should be relative to the workspace, not to the current package. +This attribute should not be needed outside of `third_party`. + +If the package declares the [feature](/reference/be/functions.html#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings +that consist of a single "Make" variable. + +`cxxopts` + +List of strings; default is `[]` + + Add these options to the C++ compilation command. +Subject to ["Make variable"](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). + `defines` + +List of strings; default is `[]` + + List of defines to add to the compile line. +Subject to ["Make" variable](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). +Each string, which must consist of a single Bourne shell token, +is prepended with `-D` and added to the compile command line to this target, +as well as to every rule that depends on it. Be very careful, since this may have +far-reaching effects. When in doubt, add define values to +[`local_defines`](#cc_binary.local_defines) instead. + `distribs` + +List of strings; default is `[]` + +`dynamic_deps` + +List of [labels](/concepts/labels); default is `[]` + + These are other `cc_shared_library` dependencies the current target depends on. + +The `cc_shared_library` implementation will use the list of +`dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the +current target's `dynamic_deps`) to decide which `cc_libraries` in +the transitive `deps` should not be linked in because they are already provided +by a different `cc_shared_library`. + + +`hdrs_check` + +String; default is `""` + + Deprecated, no-op. + `includes` + +List of strings; default is `[]` + + List of include dirs to be added to the compile line. +Subject to ["Make variable"](/reference/be/make-variables) substitution. +Each string is prepended with the package path and passed to the C++ toolchain for +expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system +with typical feature definitions will produce +`-isystem path_to_package/include_entry`. +This should only be used for third-party libraries that +do not conform to the Google style of writing #include statements. +Unlike [COPTS](#cc_binary.copts), these flags are added for this rule +and every rule that depends on it. (Note: not the rules it depends upon!) Be +very careful, since this may have far-reaching effects. When in doubt, add +"-I" flags to [COPTS](#cc_binary.copts) instead. + +The added `include` paths will include generated files as well as +files in the source tree. + +`link_extra_lib` + +[Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:link_extra_lib"` + + Control linking of extra libraries. + +By default, C++ binaries are linked against `//tools/cpp:link_extra_lib`, +which by default depends on the label flag `//tools/cpp:link_extra_libs`. +Without setting the flag, this library is empty by default. Setting the label flag +allows linking optional dependencies, such as overrides for weak symbols, interceptors +for shared library functions, or special runtime libraries (for malloc replacements, +prefer `malloc` or `--custom_malloc`). Setting this attribute to +`None` disables this behaviour. + +`linkopts` + +List of strings; default is `[]` + + Add these flags to the C++ linker command. +Subject to ["Make" variable](make-variables.html) substitution, +[Bourne shell tokenization](common-definitions.html#sh-tokenization) and +[label expansion](common-definitions.html#label-expansion). +Each string in this attribute is added to `LINKOPTS` before +linking the binary target. + +Each element of this list that does not start with `$` or `-` is +assumed to be the label of a target in `deps`. The +list of files generated by that target is appended to the linker +options. An error is reported if the label is invalid, or is +not declared in `deps`. + +`linkshared` + +Boolean; default is `False` + + Create a shared library. +To enable this attribute, include `linkshared=True` in your rule. By default +this option is off. + +The presence of this flag means that linking occurs with the `-shared` flag +to `gcc`, and the resulting shared library is suitable for loading into for +example a Java program. However, for build purposes it will never be linked into the +dependent binary, as it is assumed that shared libraries built with a +[cc\_binary](#cc_binary) rule are only loaded manually by other programs, so +it should not be considered a substitute for the [cc\_library](#cc_library) +rule. For sake of scalability we recommend avoiding this approach altogether and +simply letting `java_library` depend on `cc_library` rules +instead. + +If you specify both `linkopts=['-static']` and `linkshared=True`, +you get a single completely self-contained unit. If you specify both +`linkstatic=True` and `linkshared=True`, you get a single, mostly +self-contained unit. + +`linkstatic` + +Boolean; default is `False` + + For [`cc_binary`](/reference/be/c-cpp.html#cc_binary) and +[`cc_test`](/reference/be/c-cpp.html#cc_test): link the binary in static +mode. For `cc_library.link_static`: see below. + +By default this option is on for `cc_binary` and off for the rest. + +If enabled and this is a binary or test, this option tells the build tool to link in +`.a`'s instead of `.so`'s for user libraries whenever possible. +System libraries such as libc (but _not_ the C/C++ runtime libraries, +see below) are still linked dynamically, as are libraries for which +there is no static library. So the resulting executable will still be dynamically +linked, hence only _mostly_ static. + +There are really three different ways to link an executable: + +- STATIC with fully\_static\_link feature, in which everything is linked statically; + e.g. " `gcc -static foo.o libbar.a libbaz.a -lm`". + + + This mode is enabled by specifying `fully_static_link` in the + [`features`](/reference/be/common-definitions#features) attribute. +- STATIC, in which all user libraries are linked statically (if a static + version is available), but where system libraries (excluding C/C++ runtime libraries) + are linked dynamically, e.g. " `gcc foo.o libfoo.a libbaz.a -lm`". + + + This mode is enabled by specifying `linkstatic=True`. +- DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is + available), e.g. " `gcc foo.o libfoo.so libbaz.so -lm`". + + + This mode is enabled by specifying `linkstatic=False`. + +If the `linkstatic` attribute or `fully_static_link` in +`features` is used outside of `//third_party` +please include a comment near the rule to explain why. + +The `linkstatic` attribute has a different meaning if used on a +[`cc_library()`](/reference/be/c-cpp.html#cc_library) rule. +For a C++ library, `linkstatic=True` indicates that only +static linking is allowed, so no `.so` will be produced. linkstatic=False does +not prevent static libraries from being created. The attribute is meant to control the +creation of dynamic libraries. + +There should be very little code built with `linkstatic=False` in production. +If `linkstatic=False`, then the build tool will create symlinks to +depended-upon shared libraries in the `*.runfiles` area. + +`local_defines` + +List of strings; default is `[]` + + List of defines to add to the compile line. +Subject to ["Make" variable](/reference/be/make-variables) substitution and +[Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). +Each string, which must consist of a single Bourne shell token, +is prepended with `-D` and added to the compile command line for this target, +but not to its dependents. + `malloc` + +[Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:malloc"` + + Override the default dependency on malloc. + +By default, C++ binaries are linked against `//tools/cpp:malloc`, +which is an empty library so the binary ends up using libc malloc. +This label must refer to a `cc_library`. If compilation is for a non-C++ +rule, this option has no effect. The value of this attribute is ignored if +`linkshared=True` is specified. + +`module_interfaces` + +List of [labels](/concepts/labels); default is `[]` + + The list of files are regarded as C++20 Modules Interface. + +C++ Standard has no restriction about module interface file extension + +- Clang use cppm +- GCC can use any source file extension +- MSVC use ixx + +The use is guarded by the flag +`--experimental_cpp_modules`. + +`nocopts` + +String; default is `""` + + Remove matching options from the C++ compilation command. +Subject to ["Make" variable](/reference/be/make-variables) substitution. +The value of this attribute is interpreted as a regular expression. +Any preexisting `COPTS` that match this regular expression +(including values explicitly specified in the rule's [copts](#cc_binary.copts) attribute) +will be removed from `COPTS` for purposes of compiling this rule. +This attribute should not be needed or used +outside of `third_party`. The values are not preprocessed +in any way other than the "Make" variable substitution. + `reexport_deps` + +List of [labels](/concepts/labels); default is `[]` + +`stamp` + +Integer; default is `0` + + Whether to encode build information into the binary. Possible values: + +- `stamp = 1`: Always stamp the build information into the binary, even in + [`--nostamp`](/docs/user-manual#flag--stamp) builds. **This** + **setting should be avoided**, since it potentially kills remote caching for the + binary and any downstream actions that depend on it. + +- `stamp = 0`: Always replace build information by constant values. This + gives good build result caching. + +- `stamp = -1`: Embedding of build information is controlled by the + [`--[no]stamp`](/docs/user-manual#flag--stamp) flag. + + +Stamped binaries are _not_ rebuilt unless their dependencies change. + +`win_def_file` + +[Label](/concepts/labels); default is `None` + + The Windows DEF file to be passed to linker. + +This attribute should only be used when Windows is the target platform. +It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. + +## cc\_toolchain + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_toolchain.bzl) + +``` +cc_toolchain(name, all_files, ar_files, as_files, aspect_hints, compatible_with, compiler_files, compiler_files_without_includes, coverage_files, deprecation, dwp_files, dynamic_runtime_lib, exec_compatible_with, exec_group_compatible_with, exec_properties, exec_transition_for_inputs, features, libc_top, licenses, linker_files, module_map, objcopy_files, output_licenses, package_metadata, restricted_to, static_runtime_lib, strip_files, supports_header_parsing, supports_param_files, tags, target_compatible_with, testonly, toolchain_config, toolchain_identifier, toolchains, visibility) +``` + +Represents a C++ toolchain. + +This rule is responsible for: + + + +- Collecting all artifacts needed for C++ actions to run. This is done by + attributes such as `all_files`, `compiler_files`, + `linker_files`, or other attributes ending with `_files`). These are + most commonly filegroups globbing all required files. + +- Generating correct command lines for C++ actions. This is done using + `CcToolchainConfigInfo` provider (details below). + + +Use `toolchain_config` attribute to configure the C++ toolchain. +See also this +[page](https://bazel.build/docs/cc-toolchain-config-reference) for elaborate C++ toolchain configuration and toolchain selection documentation. + +Use `tags = ["manual"]` in order to prevent toolchains from being built and configured +unnecessarily when invoking `bazel build //...` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`all_files` + +[Label](/concepts/labels); required + + Collection of all cc\_toolchain artifacts. These artifacts will be added as inputs to all +rules\_cc related actions (with the exception of actions that are using more precise sets of +artifacts from attributes below). Bazel assumes that `all_files` is a superset +of all other artifact-providing attributes (e.g. linkstamp compilation needs both compile +and link files, so it takes `all_files`). + +This is what `cc_toolchain.files` contains, and this is used by all Starlark +rules using C++ toolchain. + +`ar_files` + +[Label](/concepts/labels); default is `None` + + Collection of all cc\_toolchain artifacts required for archiving actions. + `as_files` + +[Label](/concepts/labels); default is `None` + + Collection of all cc\_toolchain artifacts required for assembly actions. + `compiler_files` + +[Label](/concepts/labels); required + + Collection of all cc\_toolchain artifacts required for compile actions. + `compiler_files_without_includes` + +[Label](/concepts/labels); default is `None` + + Collection of all cc\_toolchain artifacts required for compile actions in case when +input discovery is supported (currently Google-only). + `coverage_files` + +[Label](/concepts/labels); default is `None` + + Collection of all cc\_toolchain artifacts required for coverage actions. If not specified, +all\_files are used. + `dwp_files` + +[Label](/concepts/labels); required + + Collection of all cc\_toolchain artifacts required for dwp actions. + `dynamic_runtime_lib` + +[Label](/concepts/labels); default is `None` + + Dynamic library artifact for the C++ runtime library (e.g. libstdc++.so). + +This will be used when 'static\_link\_cpp\_runtimes' feature is enabled, and we're linking +dependencies dynamically. + +`exec_transition_for_inputs` + +Boolean; default is `False` + + Deprecated. No-op. + `libc_top` + +[Label](/concepts/labels); default is `None` + + A collection of artifacts for libc passed as inputs to compile/linking actions. + `linker_files` + +[Label](/concepts/labels); required + + Collection of all cc\_toolchain artifacts required for linking actions. + `module_map` + +[Label](/concepts/labels); default is `None` + + Module map artifact to be used for modular builds. + `objcopy_files` + +[Label](/concepts/labels); required + + Collection of all cc\_toolchain artifacts required for objcopy actions. + `output_licenses` + +List of strings; default is `[]` + +`static_runtime_lib` + +[Label](/concepts/labels); default is `None` + + Static library artifact for the C++ runtime library (e.g. libstdc++.a). + +This will be used when 'static\_link\_cpp\_runtimes' feature is enabled, and we're linking +dependencies statically. + +`strip_files` + +[Label](/concepts/labels); required + + Collection of all cc\_toolchain artifacts required for strip actions. + `supports_header_parsing` + +Boolean; default is `False` + + Set to True when cc\_toolchain supports header parsing actions. + `supports_param_files` + +Boolean; default is `True` + + Set to True when cc\_toolchain supports using param files for linking actions. + `toolchain_config` + +[Label](/concepts/labels); required + + The label of the rule providing `cc_toolchain_config_info`. + `toolchain_identifier` + +String; default is `""` + + The identifier used to match this cc\_toolchain with the corresponding +crosstool\_config.toolchain. + +Until issue [#5380](https://github.com/bazelbuild/bazel/issues/5380) is fixed +this is the recommended way of associating `cc_toolchain` with +`CROSSTOOL.toolchain`. It will be replaced by the `toolchain_config` +attribute ( [#5380](https://github.com/bazelbuild/bazel/issues/5380)). + +## fdo\_prefetch\_hints + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/fdo_prefetch_hints.bzl) + +``` +fdo_prefetch_hints(name, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, package_metadata, profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents an FDO prefetch hints profile that is either in the workspace. +Examples: + +```lang-starlark + +fdo_prefetch_hints( + name = "hints", + profile = "//path/to/hints:profile.afdo", +) + +``` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`profile` + +[Label](/concepts/labels); required + + Label of the hints profile. The hints file has the .afdo extension +The label can also point to an fdo\_absolute\_path\_profile rule. + + +## fdo\_profile + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/fdo_profile.bzl) + +``` +fdo_profile(name, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, memprof_profile, package_metadata, profile, proto_profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents an FDO profile that is in the workspace. +Example: + +```lang-starlark + +fdo_profile( + name = "fdo", + profile = "//path/to/fdo:profile.zip", +) + +``` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`memprof_profile` + +[Label](/concepts/labels); default is `None` + + Label of the MemProf profile. The profile is expected to have +either a .profdata extension (for an indexed/symbolized memprof +profile), or a .zip extension for a zipfile containing a memprof.profdata +file. + `profile` + +[Label](/concepts/labels); required + + Label of the FDO profile or a rule which generates it. The FDO file can have one of the +following extensions: .profraw for unindexed LLVM profile, .profdata for indexed LLVM +profile, .zip that holds an LLVM profraw profile, .afdo for AutoFDO profile, .xfdo for +XBinary profile. The label can also point to an fdo\_absolute\_path\_profile rule. + `proto_profile` + +[Label](/concepts/labels); default is `None` + + Label of the protobuf profile. + + +## memprof\_profile + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/memprof_profile.bzl) + +``` +memprof_profile(name, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, package_metadata, profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents a MEMPROF profile that is in the workspace. +Example: + +```lang-starlark + +memprof_profile( + name = "memprof", + profile = "//path/to/memprof:profile.afdo", +) + +``` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`profile` + +[Label](/concepts/labels); required + + Label of the MEMPROF profile. The profile is expected to have +either a .profdata extension (for an indexed/symbolized memprof +profile), or a .zip extension for a zipfile containing a memprof.profdata +file. +The label can also point to an fdo\_absolute\_path\_profile rule. + + +## propeller\_optimize + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/propeller_optimize.bzl) + +``` +propeller_optimize(name, aspect_hints, cc_profile, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, ld_profile, package_metadata, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents a Propeller optimization profile in the workspace. +Example: + +```lang-starlark + +propeller_optimize( + name = "layout", + cc_profile = "//path:cc_profile.txt", + ld_profile = "//path:ld_profile.txt" +) + +``` + +### Arguments + +Attributes`name` + +[Name](/concepts/labels#target-names); required + +A unique name for this target. + +`cc_profile` + +[Label](/concepts/labels); required + + Label of the profile passed to the various compile actions. This file has +the .txt extension. + `ld_profile` + +[Label](/concepts/labels); required + + Label of the profile passed to the link action. This file has +the .txt extension. diff --git a/reference/be/common-definitions.mdx b/reference/be/common-definitions.mdx new file mode 100644 index 0000000..4c9db5e --- /dev/null +++ b/reference/be/common-definitions.mdx @@ -0,0 +1,794 @@ +--- +title: 'Common definitions' +--- + + + +This section defines various terms and concepts that are common to +many functions or build rules. + +## Contents + +- [Bourne shell tokenization](#sh-tokenization) +- [Label Expansion](#label-expansion) +- [Typical attributes defined by most build rules](#typical-attributes) +- [Attributes common to all build rules](#common-attributes) +- [Attributes common to all test rules (\*\_test)](#common-attributes-tests) +- [Attributes common to all binary rules (\*\_binary)](#common-attributes-binaries) +- [Configurable attributes](#configurable-attributes) +- [Implicit output targets](#implicit-outputs) + +## Bourne shell tokenization + +Certain string attributes of some rules are split into multiple +words according to the tokenization rules of the Bourne shell: +unquoted spaces delimit separate words, and single- and +double-quotes characters and backslashes are used to prevent +tokenization. + +Those attributes that are subject to this tokenization are +explicitly indicated as such in their definitions in this document. + +Attributes subject to "Make" variable expansion and Bourne shell +tokenization are typically used for passing arbitrary options to +compilers and other tools. Examples of such attributes are +`cc_library.copts` and `java_library.javacopts`. +Together these substitutions allow a +single string variable to expand into a configuration-specific list +of option words. + +## Label expansion + +Some string attributes of a very few rules are subject to label +expansion: if those strings contain a valid label as a +substring, such as `//mypkg:target`, and that label is a +declared prerequisite of the current rule, it is expanded into the +pathname of the file represented by the +[target](https://bazel.build/reference/glossary#target) `//mypkg:target`. + +Example attributes include `genrule.cmd` and +`cc_binary.linkopts`. The details may vary significantly in +each case, over such issues as: whether relative labels are +expanded; how labels that expand to multiple files are +treated, etc. Consult the rule attribute documentation for +specifics. + +## Typical attributes defined by most build rules + +This section describes attributes that are defined by many build rules, +but not all. + +AttributeDescription`data` + +List of [labels](/concepts/labels); default is `[]` + +Files needed by this rule at runtime. May list file or rule targets. Generally +allows any target. + +The default outputs and runfiles of targets in the `data` attribute +should appear in the `*.runfiles` area of any executable which is +output by or has a runtime dependency on this target. This may include data +files or binaries used when this target's +[`srcs`](#typical.srcs) are executed. See the +[data dependencies](/concepts/dependencies#data-dependencies) +section for more information about how to depend on and use data files. + +New rules should define a `data` attribute if they process +inputs which might use other inputs at runtime. Rules' implementation functions +must also [populate the target's\ +runfiles](https://bazel.build/rules/rules#runfiles) from the outputs and runfiles of any `data` attribute, +as well as runfiles from any dependency attribute which provides either +source code or runtime dependencies. + +`deps` + +List of [labels](/concepts/labels); default is `[]` + +Dependencies for this target. Generally should only list rule targets. (Though +some rules permit files to be listed directly in `deps`, this +should be avoided when possible.) + +Language-specific rules generally limit the listed targets to those with +specific [providers](https://bazel.build/extending/rules#providers). + +The precise semantics of what it means for a target to depend on another using +`deps` are specific to the kind of rule, and the rule-specific +documentation goes into more detail. For rules which process source code, +`deps` generally specifies code dependencies used by the code in +[`srcs`](#typical.srcs). + +Most often, a `deps` dependency is used to allow one module to use +symbols defined in another module written in the same programming language and +separately compiled. Cross-language dependencies are also permitted in many +cases: For example, a `java_library` target may depend on C++ code +in a `cc_library` target, by listing the latter in the +`deps` attribute. See the definition of +[dependencies](/concepts/build-ref#deps) +for more information. + +`licenses` + +List of strings; [nonconfigurable](#configurable-attributes); +default is `["none"]` + +A list of license-type strings to be used for this particular target. + +This is part of a deprecated licensing API that Bazel no longer uses. Don't +use this. + +`srcs` + +List of [labels](/concepts/labels); default is `[]` + +Files processed or included by this rule. Generally lists files directly, but +may list rule targets (like `filegroup` or `genrule`) to +include their default outputs. + +Language-specific rules often require that the listed files have particular +file extensions. + +## Attributes common to all build rules + +This section describes attributes that are implicitly added to all build +rules. + +AttributeDescription`aspect_hints` + +List of [labels](/concepts/labels); default is `[]` + +A list of arbitrary labels which is exposed to [aspects](/extending/aspects) (in +particular - aspects invoked by this rule's reverse dependencies), but isn't exposed to this rule's +own implementation. Consult documentation for language-specific rule sets for details about what +effect a particular aspect hint would have. + +You could think of an aspect hint as a richer alternative to a [tag](#common.tags): +while a tag conveys only a boolean state (the tag is either present or absent in the +`tags` list), an aspect hint can convey arbitrary structured information in its +[providers](/extending/rules#providers). + +In practice, aspect hints are used for interoperability between different language-specific +rule sets. For example, imagine you have a `mylang_binary` target which needs to depend +on an `otherlang_library` target. The MyLang-specific logic needs some additional +information about the OtherLang target in order to use it, but `otherlang_library` +doesn't provide this information because it knows nothing about MyLang. One solution might be for +the MyLang rule set to define a `mylang_hint` rule which can be used to encode that +additional information; the user can add the hint to their `otherlang_library`'s +`aspect_hints`, and `mylang_binary` can use an aspect to collect the +additional information from a MyLang-specific provider in the `mylang_hint`. + +For a concrete example, see +[`swift_interop_hint`](https://github.com/bazelbuild/rules_swift/blob/master/doc/rules.md#swift_interop_hint) +and [`swift_overlay`](https://github.com/bazelbuild/rules_swift/blob/master/doc/rules.md#swift_overlay) +in `rules_swift`. + +Best practices: + +- Targets listed in `aspect_hints` should be lightweight and minimal. +- Language-specific logic should consider only aspect hints having providers relevant to that + language, and should ignore any other aspect hints. + +`compatible_with` + +List of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); default is `[]` + +The list of environments this target can be built for, in addition to +default-supported environments. + +This is part of Bazel's constraint system, which lets users declare which +targets can and cannot depend on each other. For example, externally deployable +binaries shouldn't depend on libraries with company-secret code. See +[ConstraintSemantics](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/analysis/constraints/ConstraintSemantics.java#L46) for details. + +`deprecation` + +String; [nonconfigurable](#configurable-attributes); default is `None` + +An explanatory warning message associated with this target. +Typically this is used to notify users that a target has become obsolete, +or has become superseded by another rule, is private to a package, or is +perhaps considered harmful for some reason. It is a good idea to include +some reference (like a webpage, a bug number or example migration CLs) so +that one can easily find out what changes are required to avoid the message. +If there is a new target that can be used as a drop in replacement, it is a +good idea to just migrate all users of the old target. + +This attribute has no effect on the way things are built, but it +may affect a build tool's diagnostic output. The build tool issues a +warning when a rule with a `deprecation` attribute is +depended upon by a target in another package. + +Intra-package dependencies are exempt from this warning, so that, +for example, building the tests of a deprecated rule does not +encounter a warning. + +If a deprecated target depends on another deprecated target, no warning +message is issued. + +Once people have stopped using it, the target can be removed. + +`exec_compatible_with` + +List of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); default is `[]` + +A list of +`constraint_values` +that must be present in the execution platform of this target's default exec +group. This is in addition to any constraints already set by the rule type. +Constraints are used to restrict the list of available execution platforms. + +For more details, see +the description of +[toolchain resolution](/docs/toolchains#toolchain-resolution). +and +[exec groups](/extending/exec-groups) + +`exec_group_compatible_with` + +Dictionary of strings to lists of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); default is `{}` + +A dictionary of exec group names to lists of +`constraint_values` +that must be present in the execution platform for the given exec group. This +is in addition to any constraints already set on the exec group's definition. +Constraints are used to restrict the list of available execution platforms. + +For more details, see +the description of +[toolchain resolution](/docs/toolchains#toolchain-resolution). +and +[exec groups](/extending/exec-groups) + +`exec_properties` + +Dictionary of strings; default is `{}` + +A dictionary of strings that will be added to the `exec_properties` of a platform selected for this target. See `exec_properties` of the [platform](platforms-and-toolchains.html#platform) rule. + +If a key is present in both the platform and target-level properties, the value will be taken from the target. + +Keys can be prefixed with the name of an execution group followed by a `.` to apply them only to that particular exec group. + +`features` + +List of _feature_ strings; default is `[]` + +A feature is string tag that can be enabled or disabled on a target. The +meaning of a feature depends on the rule itself. + +This `features` attribute is combined with the [package](/reference/be/functions.html#package) level `features` attribute. For example, if +the features \["a", "b"\] are enabled on the package level, and a target's +`features` attribute contains \["-a", "c"\], the features enabled for the +rule will be "b" and "c". +[See example](https://github.com/bazelbuild/examples/blob/main/rules/features/BUILD). + +`package_metadata` + +List of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); default is the package's +`default_package_metadata` + +A list of labels that are associated metadata about this target. +Typically, the labels are simple rules that return a provider of +constant values. Rules and aspects may use these labels to perform some +additional analysis on the build graph. + +The canonical use case is that of +[rules\_license](https://github.com/bazelbuild/rules_license). +For that use case, `package_metadata` and +`default_package_metadata` is used to attach information +about a package's licence or version to targets. An aspect applied +to a top-level binary can be used to gather those and produce +compliance reports. + +`restricted_to` + +List of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); default is `[]` + +The list of environments this target can be built for, _instead_ of +default-supported environments. + +This is part of Bazel's constraint system. See +`compatible_with` +for details. + +`tags` + +List of strings; [nonconfigurable](#configurable-attributes); +default is `[]` + +_Tags_ can be used on any rule. _Tags_ on test and +`test_suite` rules are useful for categorizing the tests. +_Tags_ on non-test targets are used to control sandboxed execution of +`genrule` s and + +[Starlark](/rules/concepts) +actions, and for parsing by humans and/or external tools. + +Bazel modifies the behavior of its sandboxing code if it finds the following +keywords in the `tags` attribute of any test or `genrule` +target, or the keys of `execution_requirements` for any Starlark +action. + +- `no-sandbox` keyword results in the action or test never being + sandboxed; it can still be cached or run remotely - use `no-cache` + or `no-remote` to prevent either or both of those. + +- `no-cache` keyword results in the action or test never being + cached (locally or remotely). Note: for the purposes of this tag, the disk cache + is considered a local cache, whereas the HTTP and gRPC caches are considered + remote. Other caches, such as Skyframe or the persistent action cache, are not + affected. + +- `no-remote-cache` keyword results in the action or test never being + cached remotely (but it may be cached locally; it may also be executed remotely). + Note: for the purposes of this tag, the disk cache is considered a local cache, + whereas the HTTP and gRPC caches are considered remote. Other caches, such as + Skyframe or the persistent action cache, are not affected. + If a combination of local disk cache and remote cache are used (combined cache), + it's treated as a remote cache and disabled entirely unless `--incompatible_remote_results_ignore_disk` + is set in which case the local components will be used. + +- `no-remote-exec` keyword results in the action or test never being + executed remotely (but it may be cached remotely). + +- `no-remote` keyword prevents the action or test from being executed remotely or + cached remotely. This is equivalent to using both + `no-remote-cache` and `no-remote-exec`. + +- `no-remote-cache-upload` keyword disables upload part of remote caching of a spawn. + it does not disable remote execution. + +- `local` keyword precludes the action or test from being remotely cached, + remotely executed, or run inside the sandbox. + For genrules and tests, marking the rule with the `local = True` + attribute has the same effect. + +- `requires-network` keyword allows access to the external + network from inside the sandbox. This tag only has an effect if sandboxing + is enabled. + +- `block-network` keyword blocks access to the external + network from inside the sandbox. In this case, only communication + with localhost is allowed. This tag only has an effect if sandboxing is + enabled. + +- `requires-fakeroot` runs the test or action as uid and gid 0 (i.e., the root + user). This is only supported on Linux. This tag takes precedence over the + `--sandbox_fake_username` command-line option. + + +_Tags_ on tests are generally used to annotate a test's role in your +debug and release process. Typically, tags are most useful for C++ and Python +tests, which lack any runtime annotation ability. The use of tags and size +elements gives flexibility in assembling suites of tests based around codebase +check-in policy. + +Bazel modifies test running behavior if it finds the following keywords in the +`tags` attribute of the test rule: + +- `exclusive` will force the test to be run in the + "exclusive" mode, ensuring that no other tests are running at the + same time. Such tests will be executed in serial fashion after all build + activity and non-exclusive tests have been completed. Remote execution is + disabled for such tests because Bazel doesn't have control over what's + running on a remote machine. + +- `exclusive-if-local` will force the test to be run in the + "exclusive" mode if it is executed locally, but will run the test in parallel if it's + executed remotely. + +- `manual` keyword will exclude the target from expansion of target pattern wildcards + ( `...`, `:*`, `:all`, etc.) and `test_suite` rules + which do not list the test explicitly when computing the set of top-level targets to build/run + for the `build`, `test`, and `coverage` commands. It does not + affect target wildcard or test suite expansion in other contexts, including the + `query` command. Note that `manual` does not imply that a target should + not be built/run automatically by continuous build/test systems. For example, it may be + desirable to exclude a target from `bazel test ...` because it requires specific + Bazel flags, but still have it included in properly-configured presubmit or continuous test + runs. + + +- `external` keyword will force test to be unconditionally + executed (regardless of `--cache_test_results` + value). + + +See +[Tag Conventions](/reference/test-encyclopedia#tag-conventions) + in the Test Encyclopedia for more conventions on tags attached to test targets. +`target_compatible_with` + +List of [labels](/concepts/labels); default is `[]` + +A list of +`constraint_value` s +that must be present in the target platform for this target to be considered +_compatible_. This is in addition to any constraints already set by the +rule type. If the target platform does not satisfy all listed constraints then +the target is considered _incompatible_. Incompatible targets are +skipped for building and testing when the target pattern is expanded +(e.g. `//...`, `:all`). When explicitly specified on the +command line, incompatible targets cause Bazel to print an error and cause a +build or test failure. + +Targets that transitively depend on incompatible targets are themselves +considered incompatible. They are also skipped for building and testing. + +An empty list (which is the default) signifies that the target is compatible +with all platforms. + +All rules other than [Workspace Rules](workspace.html) support this +attribute. +For some rules this attribute has no effect. For example, specifying +`target_compatible_with` for a +`cc_toolchain` is not useful. + +See the +[Platforms](/docs/platforms#skipping-incompatible-targets) +page for more information about incompatible target skipping. + +`testonly` + +Boolean; [nonconfigurable](#configurable-attributes); default is `False` +except for test and test suite targets + +If `True`, only testonly targets (such as tests) can depend on this target. + +Equivalently, a rule that is not `testonly` is not allowed to +depend on any rule that is `testonly`. + +Tests ( `*_test` rules) +and test suites ( [test\_suite](/reference/be/general.html#test_suite) rules) +are `testonly` by default. + +This attribute is intended to mean that the target should not be +contained in binaries that are released to production. + +Because testonly is enforced at build time, not run time, and propagates +virally through the dependency tree, it should be applied judiciously. For +example, stubs and fakes that +are useful for unit tests may also be useful for integration tests +involving the same binaries that will be released to production, and +therefore should probably not be marked testonly. Conversely, rules that +are dangerous to even link in, perhaps because they unconditionally +override normal behavior, should definitely be marked testonly. + +`toolchains` + +List of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); default is `[]` + +The set of targets whose [Make variables](/reference/be/make-variables) this target is +allowed to access. These targets are either instances of rules that provide +`TemplateVariableInfo` or special targets for toolchain types built into Bazel. These +include: + +- `@bazel_tools//tools/cpp:toolchain_type` +- `@rules_java//toolchains:current_java_runtime` + +Note that this is distinct from the concept of +[toolchain resolution](/docs/toolchains#toolchain-resolution) +that is used by rule implementations for platform-dependent configuration. You cannot use this +attribute to determine which specific `cc_toolchain` or `java_toolchain` a +target will use. + +`visibility` + +List of [labels](/concepts/labels); +[nonconfigurable](#configurable-attributes); +default varies + +The `visibility` attribute controls whether the target can be +depended on by targets in other locations. See the documentation for +[visibility](/concepts/visibility). + +For targets declared directly in a BUILD file or in legacy macros called from +a BUILD file, the default value is the package's +`default_visibility` +if specified, or else `["//visibility:private"]`. For targets +declared in one or more symbolic macros, the default value is always just +`["//visibility:private"]` (which makes it useable only within the +package containing the macro's code). + +## Attributes common to all test rules (\*\_test) + +This section describes attributes that are common to all test rules. + +AttributeDescription`args` + +List of strings; subject to +[$(location)](/reference/be/make-variables#predefined_label_variables) and +["Make variable"](/reference/be/make-variables) substitution, and +[Bourne shell tokenization](#sh-tokenization); default is `[]` + +Command line arguments that Bazel passes to the target when it is +executed with `bazel test`. + +These arguments are passed before any `--test_arg` values +specified on the `bazel test` command line. + +`env` + +Dictionary of strings; values are subject to +[$(location)](/reference/be/make-variables#predefined_label_variables) and +["Make variable"](/reference/be/make-variables) substitution; default is `{}` + +Specifies additional environment variables to set when the test is executed by +`bazel test`. + +This attribute only applies to native rules, like `cc_test`, +`py_test`, and `sh_test`. It does not apply to +Starlark-defined test rules. For your own Starlark rules, you can add an "env" +attribute and use it to populate a + +[RunEnvironmentInfo](/rules/lib/providers/RunEnvironmentInfo.html) +Provider. + +[TestEnvironment](/rules/lib/toplevel/testing#TestEnvironment) + + Provider. + +`env_inherit` + +List of strings; default is `[]` + +Specifies additional environment variables to inherit from the +external environment when the test is executed by `bazel test`. + +This attribute only applies to native rules, like `cc_test`, `py_test`, +and `sh_test`. It does not apply to Starlark-defined test rules. + +`size` + +String `"enormous"`, `"large"`, `"medium"`, or +`"small"`; [nonconfigurable](#configurable-attributes); +default is `"medium"` + +Specifies a test target's "heaviness": how much time/resources it needs to run. + +Unit tests are considered "small", integration tests "medium", and end-to-end tests "large" or +"enormous". Bazel uses the size to determine a default timeout, which can be overridden using the +`timeout` attribute. The timeout is for all tests in the BUILD target, not for each +individual test. When the test is run locally, the `size` is additionally used for +scheduling purposes: Bazel tries to respect `--local_{ram,cpu}_resources` and not +overwhelm the local machine by running lots of heavy tests at the same time. + +Test sizes correspond to the following default timeouts and assumed peak local resource +usages: + +SizeRAM (in MB)CPU (in CPU cores)Default timeoutsmall201short (1 minute)medium1001moderate (5 minutes)large3001long (15 minutes)enormous8001eternal (60 minutes) + +The environment variable +`TEST_SIZE` will be set to +the value of this attribute when spawning the test. + +`timeout` + +String `"short"`, `"moderate"`, `"long"`, or +`"eternal"`; [nonconfigurable](#configurable-attributes); default is derived +from the test's `size` attribute + +How long the test is expected to run before returning. + +While a test's size attribute controls resource estimation, a test's +timeout may be set independently. If not explicitly specified, the +timeout is based on the [test's size](#test.size). The test +timeout can be overridden with the `--test_timeout` flag, e.g. for +running under certain conditions which are known to be slow. Test timeout values +correspond to the following time periods: + +Timeout ValueTime Periodshort1 minutemoderate5 minuteslong15 minuteseternal60 minutes + +For times other than the above, the test timeout can be overridden with the +`--test_timeout` bazel flag, e.g. for manually running under +conditions which are known to be slow. The `--test_timeout` values +are in seconds. For example `--test_timeout=120` will set the test +timeout to two minutes. + +The environment variable +`TEST_TIMEOUT` will be set +to the test timeout (in seconds) when spawning the test. + +`flaky` + +Boolean; [nonconfigurable](#configurable-attributes); +default is `False` + +Marks test as flaky. + +If set, executes the test up to three times, marking it as failed only if it +fails each time. By default, this attribute is set to False and the test is +executed only once. Note, that use of this attribute is generally discouraged - +tests should pass reliably when their assertions are upheld. + +`shard_count` + +Non-negative integer less than or equal to 50; default is `-1` + +Specifies the number of parallel shards +to use to run the test. + +If set, this value will override any heuristics used to determine the number of +parallel shards with which to run the test. Note that for some test +rules, this parameter may be required to enable sharding +in the first place. Also see `--test_sharding_strategy`. + +If test sharding is enabled, the environment variable ` +TEST_TOTAL_SHARDS +` will be set to this value when spawning the test. + +Sharding requires the test runner to support the test sharding protocol. +If it does not, then it will most likely run every test in every shard, which +is not what you want. + +See +[Test Sharding](/reference/test-encyclopedia#test-sharding) +in the Test Encyclopedia for details on sharding. + +`local` + +Boolean; [nonconfigurable](#configurable-attributes); +default is `False` + +Forces the test to be run locally, without sandboxing. + +Setting this to True is equivalent to providing "local" as a tag +( `tags=["local"]`). + +## Attributes common to all binary rules (\*\_binary) + +This section describes attributes that are common to all binary rules. + +AttributeDescription`args` + +List of strings; subject to +[$(location)](/reference/be/make-variables#predefined_label_variables) and +["Make variable"](/reference/be/make-variables) substitution, and +[Bourne shell tokenization](#sh-tokenization); +[nonconfigurable](#configurable-attributes); +default is `[]` + +Command line arguments that Bazel will pass to the target when it is executed +either by the `run` command or as a test. These arguments are +passed before the ones that are specified on the `bazel run` or +`bazel test` command line. + +_NOTE: The arguments are not passed when you run the target_ +_outside of Bazel (for example, by manually executing the binary in_ +_`bazel-bin/`)._ + +`env` + +Dictionary of strings; values are subject to +[$(location)](/reference/be/make-variables#predefined_label_variables) and +["Make variable"](/reference/be/make-variables) substitution; default is `{}` + +Specifies additional environment variables to set when the target is +executed by `bazel run`. + +This attribute only applies to native rules, like `cc_binary`, `py_binary`, +and `sh_binary`. It does not apply to Starlark-defined executable rules. For your own +Starlark rules, you can add an "env" attribute and use it to populate a + +[RunEnvironmentInfo](/rules/lib/providers/RunEnvironmentInfo.html) + +Provider. + +_NOTE: The environment variables are not set when you run the target_ +_outside of Bazel (for example, by manually executing the binary in_ +_`bazel-bin/`)._ + +`output_licenses` + +List of strings; default is `[]` + +The licenses of the output files that this binary generates. + +This is part of a deprecated licensing API that Bazel no longer uses. Don't +use this. + +## Configurable attributes + +Most attributes are "configurable", meaning that their values may change when +the target is built in different ways. Specifically, configurable attributes +may vary based on the flags passed to the Bazel command line, or what +downstream dependency is requesting the target. This can be used, for +instance, to customize the target for multiple platforms or compilation modes. + +The following example declares different sources for different target +architectures. Running `bazel build :multiplatform_lib --cpu x86` +will build the target using `x86_impl.cc`, while substituting +`--cpu arm` will instead cause it to use `arm_impl.cc`. + +``` +cc_library( + name = "multiplatform_lib", + srcs = select({ + ":x86_mode": ["x86_impl.cc"], + ":arm_mode": ["arm_impl.cc"] + }) +) +config_setting( + name = "x86_mode", + values = { "cpu": "x86" } +) +config_setting( + name = "arm_mode", + values = { "cpu": "arm" } +) + +``` + +The [`select()`](/reference/be/functions.html#select) function +chooses among different alternative values for a configurable attribute based +on which [`config_setting`](/reference/be/general.html#config_setting) +or [`constraint_value`](/reference/be/platforms-and-toolchains.html#constraint_value) +criteria the target's configuration satisfies. + +Bazel evaluates configurable attributes after processing macros and before +processing rules (technically, between the +[loading and analysis phases](https://bazel.build/rules/concepts#evaluation-model)). +Any processing before `select()` evaluation doesn't know which +branch the `select()` chooses. Macros, for example, can't change +their behavior based on the chosen branch, and `bazel query` can +only make conservative guesses about a target's configurable dependencies. See +[this FAQ](https://bazel.build/docs/configurable-attributes#faq) +for more on using `select()` with rules and macros. + +Attributes marked `nonconfigurable` in their documentation cannot +use this feature. Usually an attribute is nonconfigurable because Bazel +internally needs to know its value before it can determine how to resolve a +`select()`. + +See [Configurable Build Attributes](https://bazel.build/docs/configurable-attributes) for a detailed overview. + +## Implicit output targets + +_Implicit outputs in C++ are deprecated. Please refrain from using it_ +_in other languages where possible. We don't have a deprecation path yet_ +_but they will eventually be deprecated too._ + +When you define a build rule in a BUILD file, you are explicitly +declaring a new, named rule target in a package. Many build rule +functions also _implicitly_ entail one or more output file +targets, whose contents and meaning are rule-specific. + +For example, when you explicitly declare a +`java_binary(name='foo', ...)` rule, you are also +_implicitly_ declaring an output file +target `foo_deploy.jar` as a member of the same package. +(This particular target is a self-contained Java archive suitable +for deployment.) + +Implicit output targets are first-class members of the global +target graph. Just like other targets, they are built on demand, +either when specified in the top-level built command, or when they +are necessary prerequisites for other build targets. They can be +referenced as dependencies in BUILD files, and can be observed in +the output of analysis tools such as `bazel query`. + +For each kind of build rule, the rule's documentation contains a +special section detailing the names and contents of any implicit +outputs entailed by a declaration of that kind of rule. + +An important but somewhat subtle distinction between the +two namespaces used by the build system: +[labels](/concepts/labels) identify _targets_, +which may be rules or files, and file targets may be divided into +either source (or input) file targets and derived (or output) file +targets. These are the things you can mention in BUILD files, +build from the command-line, or examine using `bazel query`; +this is the _target namespace_. Each file target corresponds +to one actual file on disk (the "file system namespace"); each rule +target may correspond to zero, one or more actual files on disk. +There may be files on disk that have no corresponding target; for +example, `.o` object files produced during C++ compilation +cannot be referenced from within BUILD files or from the command line. +In this way, the build tool may hide certain implementation details of +how it does its job. This is explained more fully in +the [BUILD Concept Reference](/concepts/build-ref). diff --git a/reference/be/extra-actions.mdx b/reference/be/extra-actions.mdx new file mode 100644 index 0000000..0c16bd9 --- /dev/null +++ b/reference/be/extra-actions.mdx @@ -0,0 +1,210 @@ +--- +title: 'Extra Actions Rules' +--- + + + +## Rules + +- [action\_listener](#action_listener) +- [extra\_action](#extra_action) + +## action\_listener + +[View rule sourceopen\_in\_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/extra/ActionListenerRule.java) + +``` +action_listener(name, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, extra_actions, features, licenses, mnemonics, package_metadata, restricted_to, tags, target_compatible_with, testonly, visibility) +``` + +**WARNING:** Extra actions are deprecated. Use +[aspects](https://bazel.build/rules/aspects) +instead. + +An `action_listener` rule doesn't produce any output itself. +Instead, it allows tool developers to insert +[`extra_action`](/reference/be/extra-actions.html#extra_action) s into the build system, +by providing a mapping from action to [`extra_action`](/reference/be/extra-actions.html#extra_action). + +This rule's arguments map action mnemonics to +[`extra_action`](/reference/be/extra-actions.html#extra_action) rules. + +By specifying the option [`--experimental_action_listener=