C/C++

宏定义使用实例

  • 宏定义 描述文件 zzz.md
  // define fpga_instruction
  #ifndef DEF_ZZZ
  #error "Must define ZZZ first"
  #endif
  // DEF_ZZZ(FIELD,BITSIZE)
  DEF_ZZZ(one,1)
  DEF_ZZZ(two, 1)
  DEF_ZZZ(three, 1)
  DEF_ZZZ(four, 1)
  • 定义结构体 头文件 zzz.h
  struct ZZZ {
  #define ZZZ(field, bitsize) \
     unsigned int field : bitsize;
  #include "zzz.md"
  #undef DEF_ZZZ
  }__attribute__((packed));
  • ToString 方法 .cc 文件 zzz.cc
  #include <iostream>
  #include <string>

  #include "zzz.h"

  class ZZZ {
    ZZZ(){};
    ZZZ(){};
  public:
    string ToString(struct ZZZ *) {
  #define DEF_ZZZ(field, bitsize) \
      std::cout << (#field) << ":" << this->field << " bitsize " << std::to_string(bitsize) << std::endl;
  #include "zzz.md"
  #undef DEF_ZZZ
    }
  };

  int main() {
      ZZZ obj;
      struct ZZZ *z;
      obj.ToString(z);
  }

发表评论

电子邮件地址不会被公开。 必填项已用*标注