我是一个Bazel新手,在这里学习C++指南,尝试包括一个外部测试库(gtest):https://bazel.build/tutorials/cpp-use-cases#include-external-libraries
这是我的文件结构和工作区以及构建文件的内容:
$ tree
.
├── gtest.BUILD
├── lib
│ ├── BUILD
│ ├── hello-time.cc
│ └── hello-time.h
├── main
│ ├── BUILD
│ ├── hello-greet.cc
│ ├── hello-greet.h
│ └── hello-world.cc
├── README.md
├── test
│ ├── BUILD
│ └── hello-test.cc
└── WORKSPACE
工作空间内容:
$ cat WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "gtest",
build_file = "@//:gtest.BUILD",
url = "https://github.com/google/googletest/archive/release-1.10.0.zip",
sha256 = "94c634d499558a76fa649edb13721dce6e98fb1e7018dfaeba3cd7a083945e91",
)
Gtest.BUILD的内容:
$ cat gtest.BUILD
cc_library(
name = "main",
srcs = glob(
["src/*.cc"],
exclude = ["src/gtest-all.cc"]
),
hdrs = glob([
"include/**/*.h",
"src/*.h"
]),
copts = ["-Iexternal/gtest/include"],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
)
测试/构建的内容:
$ cat test/BUILD
cc_test(
name = "hello-test",
srcs = ["hello-test.cc"],
copts = ["-Iexternal/gtest/include"],
deps = [
"@gtest//:main",
"//main:hello-greet",
],
)
然后,我尝试运行"bazel :hello“,但是它引发了一个抱怨缺少"BUILD”文件的问题:
ERROR: An error occurred during the fetch of repository 'gtest':
Traceback (most recent call last):
...
Error in read: Unable to load package for //:gtest.BUILD: BUILD file not found in any of the following directories. Add a BUILD file to a directory to mark it as a package.
- /home/user/code/bazelbuild_examples/cpp-tutorial/stage4
然后,我在顶层目录中运行"touch BUILD“,找到一个带有类似错误消息的GitHub问题,从而消除了该错误。
Bazel现在正在下载gtest库(可以在“Bazel-stage4/bazel/gtest”下看到它),但它似乎没有提供给测试目标:
ERROR: /home/user/code/bazelbuild_examples/cpp-tutorial/stage4/test/BUILD:1:8: Compiling test/hello-test.cc failed: (Exit 1): gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer '-std=c++0x' -MD -MF ... (remaining 25 arguments skipped)
Use --sandbox_debug to see verbose messages from the sandbox
test/hello-test.cc:1:10: fatal error: gtest/gtest.h: No such file or directory
1 | #include "gtest/gtest.h"
| ^~~~~~~~~~~~~~~
compilation terminated.
为什么它找不到最普通的头/库?当您运行"bazel测试“时,目录布局是如何工作的?(即测试代码目录相对于第三方库目录在哪里?)
发布于 2022-05-23 16:24:36
我认为这个问题与你的gtest构建文件有关。首先,google测试已经提供了一个支持的Bazel构建文件,那么为什么要自己编写而不是使用它们呢?
第二:
cc_library(
name = "main",
srcs = glob(
["src/*.cc"],
exclude = ["src/gtest-all.cc"]
),
hdrs = glob([
"include/**/*.h",
"src/*.h"
]),
copts = ["-Iexternal/gtest/include"],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
)
在此规则中,c++源代码必须为标头指定的路径是“include/.*.h”。这不合适。首先,copts
影响这个规则,但不影响依赖它的其他目标。一般来说,编译器选项应该是工具链的一部分,而不是这样的规则。其次,cc_library规则有一个includes = []
参数,专门用于修复删除前导前缀的包含路径。与copts
不同,您应该使用includes
来修复路径-但是您应该使用官方的google测试构建文件,而不是自己编写,而不必处理这样的问题。
https://stackoverflow.com/questions/72355676
复制相似问题