在 CMake for Visual Studio 2010 中定义宏"disallow copy and assign"

Define macro "disallow copy and assign" in CMake for Visual Studio 2010

本文关键字:disallow copy assign and 定义 for CMake Visual Studio 2010      更新时间:2023-10-16

到目前为止,一个现有的C++多项目在QT中使用了CMake 2.8。我们希望在Visual Studio 2010中继续维护它。我使用选项 -G "Visual Studio 10" 在 CMake 中生成了 Visual Studio 项目,但现在由于以下原因我无法编译它们:

在项目中,我们使用了一个众所周知的宏,例如在这个问题中讨论了它本身。

#define DISALLOW_COPY_AND_ASSIGN(TypeName) 
  TypeName(const TypeName&);   
  void operator=(const TypeName&)

宏在 CMake 中定义,以便将其作为预处理器定义提供给编译器 (cl.exe):

add_definitions(-DDISALLOW_COPY_AND_ASSIGN(TypeName)=" TypeName(const TypeName&); void operator=(const TypeName&); ")

Visual Studio 不接受 CMake 的输出,并在代码中使用宏的任何地方抛出编译错误。正确的语法是什么,以便CMake可以为Visual Studio 2010正确生成它?

无法在 cl 的命令行上定义函数样式的宏。您可以通过将宏定义放在头文件中并使用 cl 的命令行选项/FI 传递此头文件来解决此问题。或者只是在必要时手动包含它(这可能更干净)。

我建议您一般不要使用宏,尤其是在这种情况下。如果可以使用 boost,则可以私下从 boost::noncopyable 继承。如果没有,您可以定义自己的:

class noncopyable {
   noncopyable(noncopyable const &);
   void operator=(noncopyable const&);
protected:
   noncopyable();
};
class Use : noncopyable
{
...

如果您坚持使用宏,请阅读编译器文档,了解将预处理的代码转储到文件中所需的标志,并查看宏扩展的内容。从那里您可以尝试找出出了什么问题。