【问题标题】:assignfile contents via #include to char array通过#include将文件内容分配给char数组
【发布时间】:2012-05-02 11:25:51
【问题描述】:

我想在 C++ 中执行以下操作:

static const char* data[] = { #include "mydata.hh" };

mydata.hh 的内容应该作为 char 数组分配给数据。 我已经通过#x 尝试了#include 的各种变体和(一级和二级)字符串化。到目前为止都没有工作。这真的有可能还是我错过了什么?

先谢谢了。

【问题讨论】:

    标签: c++ include char stringify


    【解决方案1】:

    你可以:

    static const char* data[] = {  // <--- new line 
    #include "mydata.hh" 
    };   // <--- don't forget semi-colon
    

    但是为什么呢?

    这都是假设 mydata.hh 包含与声明兼容的内容:

    //mydata.hh
    "bla", "goo", "foo"
    

    【讨论】:

    • 谢谢。但我的标题只包含不带引号的文本。我忘记了帖子中的分号。
    • 那么没有办法对包含的结果应用字符串化宏?
    • @litro 我不知道。
    【解决方案2】:

    预处理器仅适用于以可选空格和# 开头的语句,因此您需要将#include 放在单独的行上。

    例子:

    static const char* data[] = {
    #include "mydata.hh"
    };
    

    【讨论】:

      【解决方案3】:

      我认为重点是预处理器查找 # 代码然后执行指令,在 # 之间的点,您可以尝试将 #include "" 作为单独的行。考虑到,预处理只是一个文本解析器

      static const char* data[] = { 
              #include "mydata.hh" 
      }
      

      【讨论】:

        【解决方案4】:

        在 include 指令周围换行。您的所有字符都必须在“标题”内用逗号分隔。然后您的代码将被成功编译。虽然我确信这种编程风格看起来很糟糕。

        【讨论】:

        • 我同意它不会是美丽的。虽然我的数据文件不包含引号。虽然使用非数组 const char 我会没事的。
        猜你喜欢
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 2011-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 2021-07-04
        相关资源
        最近更新 更多