如何在传递之间共享 cl::opt 个参数?

How to share cl::opt arguments between passes?

我在我的一个 pass 中定义了一个 cl::opt 参数。

cl::opt<std::string> input("input", cl::init(""), cl::desc("the input file"), cl::value_desc("the input file"));

请问如何将这个参数分享给其他pass?我试图将它移动到一个头文件中,让另一个pass包含它,但它报告了一个多重定义错误。

您需要将选项的存储设为外部。

在一些共享头文件中声明一个变量:

extern std::string input;

并仅在您的一个来源中定义它和选项本身:

std::string input;
cl::opt<std::string, true> inputFlag("input", cl::init(""), cl::desc("the input file"), cl::value_desc("the input file"), cl::location(input));

注意添加了 cl::location(input) 参数,它指示 cl::opt 将选项值存储在 input 变量中。现在您可以从不同的 TU 访问 inputs 值,但仍然只有一个定义。

参见 Internal and External storage 部分。