使用相对路径包含生成的头文件

问题描述

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

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

(下面的例子也可以找到here

WORKSPACE.bazel

workspace(name = "TemplateRule")

main.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

config.h.in

#pragma once

#define VERSION_STR "@VERSION_STR@"

BUILD.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

根据 Best Practices 相对路径使用 .. 应该避免,但是您可以在使用 CMake 构建的遗留代码中找到这样的东西。这是巴泽尔的限制吗?或者有解决方法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)