在C宏中定义2D常量数组

时间:2019-01-21 21:56:36

标签: c gcc macros

我想在内存中加载一个静态数组,在以后的循环中(在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}, \

我已经找到了如何加载一维矢量,但是如何使用二维进行加载呢?

修改

最终目标是从中构建一个SIMD阵列:

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

并使用static const float filter[5][5]使其抱怨试图设置具有非常量值的常量。

3 个答案:

答案 0 :(得分:4)

您在=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;

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

答案 1 :(得分:2)

从意义上讲抽象

#include <stdio.h>

#define myfilter(name) name[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} }

int main()
{
    const float myfilter(filter1);
    printf("%f\n", filter1[1][1]);

    return 0;
}

答案 2 :(得分:1)

投诉是关于缺少=运算符的:

尝试一下:

#define ARRAY 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} };

稍后(例如)...

const float ARRAY;
double a = filter[0][0];  //example assignment using #defined array