首页 > 解决方案 > 在 C 宏中定义二维常量数组

问题描述

我想在内存中加载一个静态数组,在后面的循环中用作卷积核,在 C99 及更高版本中。我试过了:

/** This is the outer product of
 * filter[5] = { 1.0f / 16.0f, 4.0f / 16.0f, 6.0f / 16.0f, 4.0f / 16.0f, 1.0f / 16.0f };
 * computed at once, outside of the pixels loops, saving 25 multiplications per pixel
 * */
#define filter[5][5] { {0.00390625f, 0.015625f, 0.0234375f, 0.015625f, 0.00390625f}, \
                       {0.01562500f, 0.062500f, 0.0937500f, 0.062500f, 0.01562500f}, \
                       {0.02343750f, 0.093750f, 0.1406250f, 0.093750f, 0.02343750f}, \
                       {0.01562500f, 0.062500f, 0.0937500f, 0.062500f, 0.01562500f}, \
                       {0.00390625f, 0.015625f, 0.0234375f, 0.015625f, 0.00390625f} }

GCC 8 抱怨:

error: expected expression before « { » token
 #define filter { {0.00390625f, 0.015625f, 0.0234375f, 0.015625f, 0.00390625f}, \

我已经找到了如何加载 1D 向量,但是如何使用 2D 呢?

编辑

最终目标是从中构建一个 SIMD 数组:

static const __m128 filter_sse[5][5] = { { _mm_set1_ps(filter[0][0]),
                                         ... },
                                           ... };

并使用 astatic const float filter[5][5]会抱怨尝试使用非常量值设置常量。

标签: cgccmacros

解决方案


您省略了 和=之间filter[5][5]的内容{ {

而且,正如你所拥有的,filter不能是宏名称,因为它后面是括号

而且,您需要类型(例如float

这是一个清理后的版本:

#define DEFME float filter[5][5] = { \
    {0.00390625f, 0.015625f, 0.0234375f, 0.015625f, 0.00390625f}, \
    {0.01562500f, 0.062500f, 0.0937500f, 0.062500f, 0.01562500f}, \
    {0.02343750f, 0.093750f, 0.1406250f, 0.093750f, 0.02343750f}, \
    {0.01562500f, 0.062500f, 0.0937500f, 0.062500f, 0.01562500f}, \
    {0.00390625f, 0.015625f, 0.0234375f, 0.015625f, 0.00390625f} }

DEFME;

旁注:但是,为什么要为此使用宏?


推荐阅读