c++ - 字符串文字数组中字符串文字的编译时间大小

标签 c++ c embedded string-literals compile-time-constant

我希望在编译时找到 C 字符串文字的长度。 给定定义:

static const char * const   header_left[] =
{
    "         |          |  Raw  |  Raw  |",
    "         |          | Start |  End  |",
    "Interval#| Duration | Point | Point |",
    "---------+----------+-------+-------+",
};
const unsigned int  rows_in_header = sizeof(header_left) / sizeof(header_left[0]);

如何在不使用 strlen 的情况下找到字符串文字 header_left[2] 的长度?

在这个问题中,Determining the Length of a String Literal , 有注释将数组声明为 header_left[][4]。我不喜欢使用这种声明,因为在不改变数量常量的情况下,字符串的数量往往会发生变化。我喜欢让编译器计算字符串的数量(参见 rows_in_header 定义)和每个字符串的长度。

这适用于嵌入式系统,字符串 block 写入到串行端口。串口函数将指向数据的指针和数据的长度作为参数。串行端口代码针对 block 写入进行了优化。最好不要使用 strlen,因为那会浪费性能时间。

我在 ARM7TDMI 平台上使用 C99 和 IAR Embedded Workshop。
我包含了 c++ 标签,因为这也涉及 C++,我们将在首次产品发布后将代码迁移到 C++。

最佳答案

如果您愿意,stringref 类可以处理这个问题。它似乎比大多数其他答案更简单,并且处理行长度不同的情况:

struct stringref {
    //this is for convenience, but isn't used in this sample
    stringref(const char* p, size_t l=0) :ptr(p), len(l?l:strlen(p)) {}
    //construct from string literals
    template<size_t l> stringref(const char(&p)[l]) :ptr(p), len(l) {}
    //convert to const char*
    operator const char*() const {return ptr;}
    const char* get() const {return ptr;}
    //retrieve the length
    size_t length() const {return len;}
private:
    const char* ptr;
    size_t len;
};

stringref header_left[] =
{
    "         |          |  Raw  |  Raw  |   ",
    "         |          | Start |  End  | ",
    "Interval#| Duration | Point | Point |      ",
    "---------+----------+-------+-------+",
};

int main()
{
    const char* ptr = header_left[0]; //conversion possible
    printf("%d\n", header_left[0].length());
    printf("%d\n", header_left[1].length());
    printf("%d\n", header_left[2].length());
    printf("%d\n", header_left[3].length());
}

http://coliru.stacked-crooked.com/view?id=e244267379f84e21409db9ec39da5765-50d9cfc8a1d350e7409e81e87c2653ba

关于c++ - 字符串文字数组中字符串文字的编译时间大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323677/

相关文章:

c++ - 如何为 std::array 的列表初始化构造函数编写包装器?

c - 关于数据结构的好而广泛的书(教程)

c - 避免 C 宏中的冗余

c++ - 顶点在 Frustum 外的 OpenGL 透视投影裁剪多边形 = 错误的纹理映射?

linux - 如何在 Linux 中避免共享 IRQ 竞争

c++ - 使用递归的 C++ 中的数字模式函数

c++ - 模板类型是可选的吗?

c++ - Makefile包含错误

缺点 功能不起作用

CC2541 IAR 输出