在C++中只有头文件(模板类/函数)的情况下,如何使用Bazel



我有以下问题:假设我的项目结构是:

├── project
│   ├── include
|   |   ├── BUILD
|   |   └── library.hpp
│   ├── src
|   |   ├── BUILD
|   |   └── main.cpp
|   ├── test
|   |   ├── BUILD
|   |   └── library_test.cpp
└── WORKSPACE

library.hpp是一个包含模板类实现的文件,它包含在main.cpplibrary_test.cpp中。

如何准备BUILD文件,这样我在编译library_test.cppmain.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",
]
)

上面我也试着用hdrstextual_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

相关内容

  • 没有找到相关文章

最新更新