I use bazel to build a small c++ program, program directory structure is like this
.
├── bazel-bin -> /data/.cache/execroot/__main__/bazel-out/k8-fastbuild/bin
├── bazel-main -> /data/.cache/execroot/__main__
├── bazel-out -> /data/.cache/execroot/__main__/bazel-out
├── bazel-testlogs -> /data/.cache/execroot/__main__/bazel-out/k8-fastbuild/testlogs
├── BUILD
├── library
│ ├── BUILD
│ ├── foo.cc
│ └── foo.h
├── main.cpp
└── WORKSPACE
this is BUILD file in library
package(default_visibility = ["//visibility:public"])
cc_library(
name = "foo",
srcs = ["foo.cc"],
hdrs = ["foo.h"]
)
this is BUILD file in main directory
cc_binary(
name = "myapp",
srcs = ["main.cpp"],
deps = [
"//library:foo",
],
)
the structure of directory bazel-out/k8-fastbuild/bin is like this
.
├── library
│ ├── libfoo.a
│ ├── libfoo.a-2.params
│ ├── libfoo.so
│ ├── libfoo.so-2.params
│ └── _objs
│ └── foo
│ ├── foo.pic.d
│ └── foo.pic.o
├── myapp
├── myapp-2.params
├── myapp.runfiles
│ ├── __main__
│ │ └── myapp -> /data/.cache/execroot/__main__/bazel-out/k8-fastbuild/bin/myapp
│ └── MANIFEST
├── myapp.runfiles_manifest
└── _objs
└── myapp
├── main.pic.d
└── main.pic.o
I know that pid stands for position independent code. I want to know whether Bazel uses the libfoo.a or foo.pic.o when linking with main, and why bazel generates these two types of files, libfoo.xx and foo.pic.xx. what's the difference between them?
when I move library directory out of main, then use local_repository in WORKSPACE to specify library foo, after bazel build, I find that there is no libfoo.xx files generated, only foo.pic.xx file can be found in bazel-out directory,
foo.pic.o
, an object file, and foo.pic.d
, a dependency file, are the outputs of compiling foo.cc
. Traditionally, object files are put into ar
archives, which can be liked into top-level shared libraries or binaries. If you bazel build
a cc_library
rule directly, Bazel will compile the sources files within it and produce an ar
archive. However, modern linkers commonly used on Linux can take the object files directly without needing the archive indirection. Bazel detects this linker feature and uses it to avoid archives if possible. In the example in the question, building only the top-level myapp
does not require libfoo.a
to be created.