0

目前,我尝试使用最初使用 CMake 作为构建系统的Bazel (4.1.0) 构建一个库。

我在尝试使用相对路径(在它使用的 CMake 构建中configure_file)包含生成的头文件时遇到问题:

(下面的例子也可以在这里找到)

工作空间.bazel

workspace(name = "TemplateRule")

主.cpp

#include "kernel/some_header.h"
#include <iostream>

int main() {
    std::cout << VERSION_STR << std::endl;
}

内核/some_header.h

#pragma once

#include "../config.h"   // <---- include config.h using a relative path

配置.h.in

#pragma once

#define VERSION_STR "@VERSION_STR@"

构建.bazel

load("//bazel:template_rule.bzl", "template_rule")

template_rule(
    name = "config_h",
    src = "config.h.in",
    out = "config.h",
    substitutions = {
        "@VERSION_STR@": "1.0.3",
    },
)

cc_binary(
    name = "HelloWorld",
    srcs = [
        "main.cpp",
        "kernel/some_header.h",
        ":config_h",
    ],
)

bazel/BUILD.bazel : <空>

bazel/template_rule.bzl

# Copied from https://github.com/tensorflow/tensorflow/blob/master/third_party/common.bzl

'''
    Copyright 2019 The TensorFlow Authors. All Rights Reserved.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
'''
    
def template_rule_impl(ctx):
    out = ctx.outputs.out
    ctx.actions.expand_template(
        template = ctx.file.src,
        output = ctx.outputs.out,
        substitutions = ctx.attr.substitutions,
    )
    return [CcInfo(
        compilation_context = cc_common.create_compilation_context(
            includes = depset([out.dirname]),
            headers = depset([out]),
        ),
    )]

template_rule = rule(
    attrs = {
        "src": attr.label(
            mandatory = True,
            allow_single_file = True,
        ),
        "substitutions": attr.string_dict(mandatory = True),
        "out": attr.output(mandatory = True),
    },
    # output_to_genfiles is required for header files.
    output_to_genfiles = True,
    implementation = template_rule_impl,
)

当我跑bazel build //...

我得到错误:

In file included from main.cpp:1:
kernel/some_header.h:3:10: fatal error: ../config.h: No such file or directory
    3 | #include "../config.h"
      |          ^~~~~~~~~~~~~

当我将其包含在内config.h并从所有内容中main.cpp删除时,kernel/some_header.h一切都会按预期进行。

任何想法如何相对路径.../config.h工作?

创建文件config.h并手动编译代码按预期工作:

g++  main.cpp kernel/some_header.h config.h

根据最佳实践..,应避免使用相对路径,但您可以在使用 CMake 构建的遗留代码中找到此类内容。这是巴泽尔的限制吗?还是有解决方法?

4

0 回答 0