【问题标题】:How best can I programmatically apply `__attribute__ ((unused))` to these auto-generated objects?我怎样才能以编程方式将 `__attribute__ ((unused))` 应用于这些自动生成的对象?
【发布时间】:2011-12-01 09:48:47
【问题描述】:

在我的makefile 中,我有以下目标,它使用xxd -i 将文本/HTML 资源“编译”成unsigned char 数组。

我将结果包装在匿名命名空间和标头保护中,以确保翻译单元内部和之间的多重包含安全。

templates.h:
    @echo "#ifndef TEMPLATES_H" > templates.h
    @echo "#define TEMPLATES_H" >> templates.h
    @echo "// Auto-generated file! Do not modify!" >> templates.h
    @echo "// NB: arrays are not null-terminated" >> templates.h
    @echo "// (anonymous namespace used to force internal linkage)" >> templates.h
    @echo "namespace {" >> templates.h
    @echo "namespace templates {" >> templates.h
    @cd templates;\
    for i in * ;\
    do \
        echo "Compiling $$i...";\
        xxd -i $$i >> ../templates.h;\
    done;\
    cd ..
    @echo "}" >> templates.h
    @echo "}" >> templates.h
    @echo "#endif" >> templates.h

如果我只有一个这样的资源,输出看起来像这样(实际内容已编辑)

#ifndef TEMPLATES_H
#define TEMPLATES_H
// Auto-generated file! Do not modify!
// NB: arrays are not null-terminated
// (anonymous namespace used to force internal linkage)
namespace {
namespace templates {
unsigned char alert_email_finished_events_html[] = {
  0x3c, 0x74, 0x61, 0x62, 0x6c, 0x0d, 0x0a
};
unsigned int alert_email_finished_events_html_len = 7;
}
}
#endif

以编程方式将 GCC 的 __attribute__ ((unused)) 应用于这些字符数组的最佳方法是什么?我不希望 GCC 警告我最终未在任何给定 TU 中使用的任何资源,但是我也不想完全关闭“未使用的变量”警告。

【问题讨论】:

  • 有什么理由不使用-fvisibility=hidden 进行编译,只导出那些你想有外部链接的符号?这样您就可以避免在任何地方都包含模板。
  • @MatthieuM。似乎很麻烦,因为我希望在其他地方默认外部链接。我想要一种只影响模板的方法,而不影响其他任何东西。我暂时不太担心到处复制模板,因为我只在一个 TU 中使用它们;这种方法只是为某人第一次来和#includes template.h 在另一个 TU 中提供错误缓解。如果它最终出现在很多 TU 中,那么当然,更聪明的东西可能值得设计。
  • @MatthieuM。 (另一个答案是我还没有完全“得到”-fvisibility="hidden"。:P)
  • 另一种解决方案是选择性地将__attribute__ ((visibility ("hidden")) 应用于这些符号,而不是将它们标记为unused。我对未使用的问题是使用 标记为未使用的符号可能会导致警告(如果不是立即,可能在将来)。
  • @MatthieuM.:真的吗? doc 表示“附加到函数的此属性意味着该函数可能未使用。GCC 不会对此函数产生警告。”

标签: c++ gcc makefile xxd


【解决方案1】:

我认为快速的sed 应该可以工作,因为xxd -i 的输出非常有规律:

xxd -i $$i | sed -e 's/ =/ __attribute__((unused)) =/' >> ../templates.h

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    相关资源
    最近更新 更多