有没有办法告诉编译器忽略C中的某些代码块?

问题描述

我在C / CUDA上编写了一段代码,该代码将根据用户选择的值给出某些输出用户可以编辑此定义-#define WIDTH 128 基于以下代码将被执行

/*              INTERNAL PROCESSING,IGnorE THIS SECTION                */
//Here we are initializing our datatype according to the width user entered and a random value which we will use to fill in our vectors
#if (WIDTH==8)
        typedef int8_t  dtype;
        dtype num = 4;
        #define isstruct 0
#elif (WIDTH==16)
        typedef int16_t dtype;
        dtype num = 4;
        #define isstruct 0
#elif (WIDTH==32)
        typedef int32_t dtype;
        dtype num = 4;
        #define isstruct 0
#elif (WIDTH==64)
        typedef int64_t dtype;
        dtype num = 4;
        #define isstruct 0
#elif (WIDTH==128)
        typedef struct dtype{
                int temp1;
                int temp2;
                int temp3;
                int temp4;
        }dtype;
        dtype num={4,4,4};
        #define isstruct 1
#endif

稍后在代码中,我创建了一个指针,并使用malloc分配了一些空间,我用'num'中包含的值填充了该空间

dtype *a_d;
a_d=(dtype *)malloc( some_size_I_chose);
for(....)
{
    a_d[i]=num;
}

最后,我只想验证一切是否按计划进行,所以我编写了此验证循环-

               if(isstruct == 0)
                {
                        if( a_d[i] != num )
                        {
                                printf("Error Detected at position %d\n",i);
                                *dangerflag=1;
                        }
                }
                //FOR HANDLING STRUCTS FOR 128 BITS
                else if(isstruct == 1)
                {
                        if( (a_d[i].temp1 != num.temp1) && (a_d[i].temp2 != num.temp2) && (a_d[i].temp3 != num.temp3) && (a_d[i].temp4 != num.temp4))
                        {
                                printf("Error Detected at position %d\n",i);
                                *dangerflag=1;
                        }
                }

但是,如果用户输入除128以外的任何值,则编译器会打印出错误

error: expression must have class type

现在,我可以确定,由于#语句是预处理指令,因此预处理器定义了数据类型(如果struct定义的值不是128,则不是结构),由于第二个代码块,编译器在编译期间会出错在我的验证部分中,涉及与结构相关的操作。一种解决方案是将所有其他数据类型都定义为类似这样的结构,并对程序的其余部分进行后续更改-

#if (WIDTH==8)
        typedef struct dtype{
                int8_t  val;
                }dtype;
        dtype num = {4};

但是我想知道是否可以告诉编译器不要根据某种条件编译某些代码。可能吗? 还有其他更好的方法解决这个问题吗?

解决方法

但是我想知道是否可以告诉编译器不要根据某种条件编译某些代码。有可能吗?

您实际上已经做到了。

Container(
    child: PagewiseGridView.count(
    shrinkWrap: true,pageSize: 6,crossAxisCount: 3,mainAxisSpacing: 8.0,crossAxisSpacing: 8.0,childAspectRatio: 0.555,padding: EdgeInsets.all(15.0),noItemsFoundBuilder: (_) => Text("Nichts gefunden"),itemBuilder: (context,entry,index) {
      print(entry);
      return Text("Hey");
    },pageFuture: (pageIndex) {
      return getDemoImagesJson();
    },))

再做一次。