我有以下问题:假设我的项目结构是:
├── project
│ ├── include
| | ├── BUILD
| | └── library.hpp
│ ├── src
| | ├── BUILD
| | └── main.cpp
| ├── test
| | ├── BUILD
| | └── library_test.cpp
└── WORKSPACE
library.hpp
是一个包含模板类实现的文件,它包含在main.cpp
和library_test.cpp
中。
如何准备BUILD
文件,这样我在编译library_test.cpp
和main.cpp
时就不会出现编译错误,比如:
src/main.cpp:2:10: fatal error: shared_ptr.hpp: No such file or directory
2 | #include "library.hpp"
| ^~~~~~~~~~~~~~~~
compilation terminated.
我尝试的是:
include/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "library",
srcs = ["library.hpp"],
includes = ["include"],
visibility = [
"//visibility:public",
]
)
上面我也试着用hdrs
和textual_hdrs
代替srcs
。
test/BUILD
:
load("@rules_cc//cc:defs.bzl", "cc_test")
cc_test(
name = "library_test",
srcs = ["library_test.cpp"],
deps = [
"@gtest//:gtest",
"@gtest//:gtest_main",
],
includes = ["include"],
copts = ["-Iproject/include"],
)
为了彻底了解我的WORKSPACE
:
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "gtest",
remote = "https://github.com/google/googletest",
branch = "v1.10.x",
)
根据我在网上看到的官方集市教程、一些演示或类似问题,我有一个问题需要自己解决。它们只显示在库中编写的函数的定义在cpp文件中并且可以编译为对象文件的情况下使用cc_library。
# BUILD
cc_library(
name = "library",
hdrs= ["include/library.hpp"],
includes = ["include"],
visibility = [
"//visibility:public",
]
)
cc_test(
name = "library_test",
srcs = ["test/library_test.cpp"],
deps = [
"@gtest//:gtest_main", # gtest_main already contains gtest
":library"
],
)
cc_binary(
name = "binary",
srcs = ["src/main.cpp"],
deps = [
":library"
],
)
注意:
- 使用
hdrs
,因为依赖目标看不到srcs
- 不要将单独的
BUILD
文件用于src
/include
/test
目录。在Bazel中,您应该创建按功能而不是按层定向的包 - 在您的代码中,
library_test
目标不会看到来自library
目标的标头,您必须通过deps
属性将其作为依赖项传递。Bazel使用沙箱TL;DR:操作看不到未明确定义为依赖项的文件 - 请勿使用
copts = ["-Iproject/include"]
。当一切都做得正确时,Bazel会为您做这件事:在这种情况下,您必须向library
目标添加一个includes
属性。Include路径将在library_test
中设置,因为测试目标取决于library