目前,我在CMake中使用变量MYPROJECT_CURRENT_HEADERS
列出所有标题。当我使用Qt时,我的CMakeLists.txt包含:
QT4_WRAP_CPP(MYPROJECT_CURRENT_MOC ${MYPROJECT_CURRENT_HEADERS})
问题是所有标头都由moc处理,即使是那些没有Q_OBJECT
的标头:因此它会生成许多空文件。
是否存在“grep”/ detect如果文件包含字符串Q_OBJECT
的解决方案,如果是这种情况,请将其添加到MYPROJECT_CURRENT_MOC
?
谢谢
答案 0 :(得分:5)
我不知道从列表中选择包含字符串的标题的简单命令,但您始终可以循环查找所有此类标题:
set(HEADERS_HAVING_Q_OBJECT)
foreach(header ${MYPROJECT_CURRENT_HEADERS})
file(STRINGS "${header}" lines REGEX "Q_OBJECT")
if(lines)
list(APPEND HEADERS_HAVING_Q_OBJECT "${header}")
endif()
endforeach()
但是这个解决方案有其自身的缺点:如果您在其中一个已过滤的文件中添加Q_OBJECT
,则需要手动重新运行cmake。否则,在构建过程中不会自动生成新文件的moc代码。
答案 1 :(得分:5)
即将发布的CMake 2.8.6中有一个名为“AUTOMOC”的新目标属性,可以帮助你。
此功能的测试(您可以将其用作指南或示例)可在此处找到:
非常简单的CMakeLists.txt文件在这里:
如果您使用此功能,cmake将扫描Q_OBJECT的标题并自动为您运行moc。
如果您想在CMake 2.8.6的最终版本之前试用,可以在此处下载其中一个候选版本:
http://cmake.org/files/v2.8/?C=M;O=D
“-rc2”文件包含AUTOMOC属性。
以下是运行“cmake --help-property AUTOMOC”的帮助文本:
cmake version 2.8.6-rc2 AUTOMOC Should the target be processed with automoc (for Qt projects). AUTOMOC is a boolean specifying whether CMake will handle the Qt moc preprocessor automatically, i.e. without having to use the QT4_WRAP_CPP() macro. Currently Qt4 is supported. When this property is set to TRUE, CMake will scan the source files at build time and invoke moc accordingly. If an #include statement like #include "moc_foo.cpp" is found, the Q_OBJECT class declaration is expected in the header, and moc is run on the header file. If an #include statement like #include "foo.moc" is found, then a Q_OBJECT is expected in the current source file and moc is run on the file itself. Additionally, all header files are parsed for Q_OBJECT macros, and if found, moc is also executed on those files. The resulting moc files, which are not included as shown above in any of the source files are included in a generated _automoc.cpp file, which is compiled as part of the target.This property is initialized by the value of the variable CMAKE_AUTOMOC if it is set when a target is created.