编译时初始化的数组元素的C结构初始化数量

时间:2020-01-30 15:26:43

标签: c arrays struct compilation

INSERTDATA.CommandText = "INSERT INTO [table3]  values (1,'aaaa','25-01-2012');";

我正在尝试找到一种方法,用在 compile 时初始化的数组中的项目数填充.num_items字段。我知道为什么该代码示例不起作用,我想知道是否有任何方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

一个不可移植的技巧是使用__COUNTER__预处理程序扩展。它不是标准的C功能,但在最新的gcc,clang和msvc编译器中应受支持。

在每次求值之后,预处理器都会递增计数器的值,因此您必须使用以下类似的方法来强制求值:

// in case __COUNTER__ was previously used in a different header
const static int initial_counter = __COUNTER__; 

#ifdef ITEM1 
  const static int item1_defined = __COUNTER__; // +1
#endif
#ifdef ITEM2
  const static int item2_defined = __COUNTER__; // +1
#endif
#ifdef ITEM3
  const static int item3_defined = __COUNTER__; // +1
#endif

// must subtract 1 because this line also evaluates __COUNTER__
const static int total_item_count = (__COUNTER__) - initial_counter - 1;

然后:

items_list_t item_list = 
{
    .items = { ... },
    .num_items = total_item_count
}

更可移植的预处理器替代方法是使用Boost,它应该更可移植(但是它是为C ++编写的,因此您可能必须将一些细节移植到C上),或者使用代码生成器(推荐)

将代码生成器包含在您的构建脚本中将生成实际的源代码,您可以介入并在需要时进行调试。预处理程序黑客很容易失控。