我无法使用 bazel 正确添加外部依赖项



我试着测试"Hello World">

我有以下的项目结构:

WORKSPACE
/dependencies
BUILD
BUILD.gtest
/test
BUILD

WORKSPACE的结构如下:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# gtest
http_archive(
name = "gtest",
url = "https://github.com/google/googletest/archive/release-1.10.0.zip",
sha256 = "94c634d499558a76fa649edb13721dce6e98fb1e7018dfaeba3cd7a083945e91",
build_file = "@//dependencies:BUILD.gtest",
strip_prefix = "googletest-release-1.10.0",
)

构建。Gtest的结构如下:

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"],
)

test BUILD的结构如下:

cc_test(
name = "unittests",
srcs = ["scanner_test.cc"],
copts = ["-Iexternal/gtest/include"],
deps = [
"//scanner:scanner",
"@gtest//:main"
]
)

当我执行

bazel build //test:unittests

INFO: Analyzed target //test:unittests (26 packages loaded, 315 targets configured).
INFO: Found 1 target...
ERROR: ../test/BUILD:1:8: Compiling test/scanner_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 argument(s) skipped)
Use --sandbox_debug to see verbose messages from the sandbox
test/scanner_test.cc:1:10: fatal error: gtest/gtest.h: No such file or directory
1 | #include "gtest/gtest.h"
|          ^~~~~~~~~~~~~~~
compilation terminated.
Target //test:unittests failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 2.314s, Critical Path: 0.08s
INFO: 2 processes: 2 internal.
FAILED: Build did NOT complete successfully

正如另一个答案所提到的:

不需要BUILD.gtest文件。

因为gtest repo/release archive已经提供了一个

你自己的行为不像你预期的那样的原因是你试图通过操纵copts来指向标头,这只适用于构建一个特定的cc_library目标(来自链接文档):

这些标志只对编译这个目标有效,对它的依赖项无效,所以要小心其他地方包含的头文件。

然而,要将这些接口暴露给使用它的其他目标,您需要使用includes(还是docs):

与COPTS不同,这些标志是为该规则以及依赖于它的每个规则添加的。

不需要BUILD.gtest文件。

WORKSPACE.bazel:

workspace(name = "GTestDemo")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "gtest",
url = "https://github.com/google/googletest/archive/release-1.10.0.tar.gz",
sha256 = "9dc9157a9a1551ec7a7e43daea9a694a0bb5fb8bec81235d8a1e6ef64c716dcb",
strip_prefix = "googletest-release-1.10.0",
)

BUILD.bazel:

cc_test(
name = "tests",
srcs = ["test.cpp"],
deps = [
"@gtest//:gtest",
"@gtest//:gtest_main",
],
)

test.cpp:

#include <iostream>
#include <fstream>
#include "gtest/gtest.h"
using namespace std;
TEST(sample_test_case, sample_test) {
EXPECT_EQ(1, 1);
}

用Bazel4.1.0测试。

相关内容

  • 没有找到相关文章

最新更新