1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
3 #include "cmQtAutoGenInitializer.h"
7 #include <initializer_list>
12 #include <unordered_set>
16 #include <cm/algorithm>
17 #include <cm/iterator>
19 #include <cmext/algorithm>
21 #include <cm3p/json/value.h>
22 #include <cm3p/json/writer.h>
24 #include "cmsys/SystemInformation.hxx"
26 #include "cmCustomCommand.h"
27 #include "cmCustomCommandLines.h"
28 #include "cmGeneratedFileStream.h"
29 #include "cmGeneratorExpression.h"
30 #include "cmGeneratorTarget.h"
31 #include "cmGlobalGenerator.h"
32 #include "cmLinkItem.h"
33 #include "cmListFileCache.h"
34 #include "cmLocalGenerator.h"
35 #include "cmMakefile.h"
36 #include "cmMessageType.h"
37 #include "cmPolicies.h"
38 #include "cmProperty.h"
39 #include "cmQtAutoGen.h"
40 #include "cmQtAutoGenGlobalInitializer.h"
41 #include "cmSourceFile.h"
42 #include "cmSourceFileLocationKind.h"
43 #include "cmSourceGroup.h"
45 #include "cmStateTypes.h"
46 #include "cmStringAlgorithms.h"
47 #include "cmSystemTools.h"
53 unsigned int GetParallelCPUCount()
55 static unsigned int count = 0;
56 // Detect only on the first call
58 cmsys::SystemInformation info;
61 cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
66 std::string FileProjectRelativePath(cmMakefile* makefile,
67 std::string const& fileName)
71 std::string pSource = cmSystemTools::RelativePath(
72 makefile->GetCurrentSourceDirectory(), fileName);
73 std::string pBinary = cmSystemTools::RelativePath(
74 makefile->GetCurrentBinaryDirectory(), fileName);
75 if (pSource.size() < pBinary.size()) {
76 res = std::move(pSource);
77 } else if (pBinary.size() < fileName.size()) {
78 res = std::move(pBinary);
87 * Tests if targetDepend is a STATIC_LIBRARY and if any of its
88 * recursive STATIC_LIBRARY dependencies depends on targetOrigin
89 * (STATIC_LIBRARY cycle).
91 bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
92 cmGeneratorTarget const* targetDepend,
93 std::string const& config)
96 if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
97 (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
98 std::set<cmGeneratorTarget const*> knownLibs;
99 std::deque<cmGeneratorTarget const*> testLibs;
101 // Insert initial static_library dependency
102 knownLibs.insert(targetDepend);
103 testLibs.push_back(targetDepend);
105 while (!testLibs.empty()) {
106 cmGeneratorTarget const* testTarget = testLibs.front();
107 testLibs.pop_front();
108 // Check if the test target is the origin target (cycle)
109 if (testTarget == targetOrigin) {
113 // Collect all static_library dependencies from the test target
114 cmLinkImplementationLibraries const* libs =
115 testTarget->GetLinkImplementationLibraries(config);
116 if (libs != nullptr) {
117 for (cmLinkItem const& item : libs->Libraries) {
118 cmGeneratorTarget const* depTarget = item.Target;
119 if ((depTarget != nullptr) &&
120 (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
121 knownLibs.insert(depTarget).second) {
122 testLibs.push_back(depTarget);
131 /** Sanitizes file search paths. */
132 class SearchPathSanitizer
135 SearchPathSanitizer(cmMakefile* makefile)
136 : SourcePath_(makefile->GetCurrentSourceDirectory())
139 std::vector<std::string> operator()(
140 std::vector<std::string> const& paths) const;
143 std::string SourcePath_;
146 std::vector<std::string> SearchPathSanitizer::operator()(
147 std::vector<std::string> const& paths) const
149 std::vector<std::string> res;
150 res.reserve(paths.size());
151 for (std::string const& srcPath : paths) {
152 // Collapse relative paths
153 std::string path = cmSystemTools::CollapseFullPath(srcPath, SourcePath_);
154 // Remove suffix slashes
155 while (cmHasSuffix(path, '/')) {
158 // Accept only non empty paths
160 res.emplace_back(std::move(path));
166 /** @brief Writes a CMake info file. */
171 void Set(std::string const& key, std::string const& value)
175 void SetConfig(std::string const& key,
176 cmQtAutoGenInitializer::ConfigString const& cfgStr);
177 void SetBool(std::string const& key, bool value) { Value_[key] = value; }
178 void SetUInt(std::string const& key, unsigned int value)
184 template <typename CONT>
185 static bool MakeArray(Json::Value& jval, CONT const& container);
187 template <typename CONT>
188 static void MakeStringArray(Json::Value& jval, CONT const& container);
191 template <typename CONT>
192 void SetArray(std::string const& key, CONT const& container);
193 template <typename CONT>
195 std::string const& key,
196 cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
198 // -- Array of arrays
199 template <typename CONT, typename FUNC>
200 void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
202 // -- Save to json file
203 bool Save(std::string const& filename);
209 void InfoWriter::SetConfig(std::string const& key,
210 cmQtAutoGenInitializer::ConfigString const& cfgStr)
212 Set(key, cfgStr.Default);
213 for (auto const& item : cfgStr.Config) {
214 Set(cmStrCat(key, '_', item.first), item.second);
218 template <typename CONT>
219 bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
221 jval = Json::arrayValue;
222 std::size_t const listSize = cm::size(container);
226 jval.resize(static_cast<unsigned int>(listSize));
230 template <typename CONT>
231 void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
233 if (MakeArray(jval, container)) {
234 Json::ArrayIndex ii = 0;
235 for (std::string const& item : container) {
241 template <typename CONT>
242 void InfoWriter::SetArray(std::string const& key, CONT const& container)
244 MakeStringArray(Value_[key], container);
247 template <typename CONT, typename FUNC>
248 void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
251 Json::Value& jval = Value_[key];
252 if (MakeArray(jval, container)) {
253 Json::ArrayIndex ii = 0;
254 for (auto const& citem : container) {
255 Json::Value& aval = jval[ii++];
256 aval = Json::arrayValue;
262 template <typename CONT>
263 void InfoWriter::SetConfigArray(
264 std::string const& key,
265 cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
267 SetArray(key, cfgStr.Default);
268 for (auto const& item : cfgStr.Config) {
269 SetArray(cmStrCat(key, '_', item.first), item.second);
273 bool InfoWriter::Save(std::string const& filename)
275 cmGeneratedFileStream fileStream;
276 fileStream.SetCopyIfDifferent(true);
277 fileStream.Open(filename, false, true);
282 Json::StyledStreamWriter jsonWriter;
284 jsonWriter.write(fileStream, Value_);
289 return fileStream.Close();
292 } // End of unnamed namespace
294 cmQtAutoGenInitializer::cmQtAutoGenInitializer(
295 cmQtAutoGenGlobalInitializer* globalInitializer,
296 cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
297 bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
298 bool globalAutoRccTarget)
299 : GlobalInitializer(globalInitializer)
300 , GenTarget(genTarget)
301 , GlobalGen(genTarget->GetGlobalGenerator())
302 , LocalGen(genTarget->GetLocalGenerator())
303 , Makefile(genTarget->Makefile)
304 , PathCheckSum(genTarget->Makefile)
305 , QtVersion(qtVersion)
307 AutogenTarget.GlobalTarget = globalAutogenTarget;
308 Moc.Enabled = mocEnabled;
309 Uic.Enabled = uicEnabled;
310 Rcc.Enabled = rccEnabled;
311 Rcc.GlobalTarget = globalAutoRccTarget;
314 bool cmQtAutoGenInitializer::InitCustomTargets()
317 this->MultiConfig = this->GlobalGen->IsMultiConfig();
318 this->ConfigDefault = this->Makefile->GetConfigurations(this->ConfigsList);
319 if (this->ConfigsList.empty()) {
320 this->ConfigsList.push_back(this->ConfigDefault);
326 this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
328 unsigned long iVerb = 0;
329 if (cmStrToULong(def, &iVerb)) {
331 this->Verbosity = static_cast<unsigned int>(iVerb);
333 // Non numeric verbosity
344 this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
345 if (folder == nullptr) {
346 folder = this->Makefile->GetState()->GetGlobalProperty(
347 "AUTOGEN_TARGETS_FOLDER");
349 // Inherit FOLDER property from target (#13688)
350 if (folder == nullptr) {
351 folder = this->GenTarget->GetProperty("FOLDER");
353 if (folder != nullptr) {
354 this->TargetsFolder = *folder;
358 // Check status of policy CMP0071 regarding handling of GENERATED files
359 switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
360 case cmPolicies::WARN:
361 // Ignore GENERATED files but warn
362 this->CMP0071Warn = true;
364 case cmPolicies::OLD:
365 // Ignore GENERATED files
367 case cmPolicies::REQUIRED_IF_USED:
368 case cmPolicies::REQUIRED_ALWAYS:
369 case cmPolicies::NEW:
370 // Process GENERATED files
371 this->CMP0071Accept = true;
375 // Check status of policy CMP0100 regarding handling of .hh headers
376 switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
377 case cmPolicies::WARN:
378 // Ignore but .hh files but warn
379 this->CMP0100Warn = true;
381 case cmPolicies::OLD:
384 case cmPolicies::REQUIRED_IF_USED:
385 case cmPolicies::REQUIRED_ALWAYS:
386 case cmPolicies::NEW:
388 this->CMP0100Accept = true;
392 // Common directories
394 // Collapsed current binary directory
395 std::string const cbd = cmSystemTools::CollapseFullPath(
396 std::string(), this->Makefile->GetCurrentBinaryDirectory());
399 this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
401 cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
404 this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
405 if (this->Dir.Build.empty()) {
407 cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
409 cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
410 // Cleanup build directory
411 this->AddCleanFile(this->Dir.Build);
414 this->Dir.Work = cbd;
415 cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
418 ConfigFileNames(this->Dir.Include, cmStrCat(this->Dir.Build, "/include"),
420 this->Dir.IncludeGenExp = this->Dir.Include.Default;
421 if (this->MultiConfig) {
422 this->Dir.IncludeGenExp += "_$<CONFIG>";
426 // Moc, Uic and _autogen target settings
427 if (this->MocOrUicEnabled()) {
428 // Init moc specific settings
429 if (this->Moc.Enabled && !InitMoc()) {
433 // Init uic specific settings
434 if (this->Uic.Enabled && !InitUic()) {
438 // Autogen target name
439 this->AutogenTarget.Name =
440 cmStrCat(this->GenTarget->GetName(), "_autogen");
442 // Autogen target parallel processing
444 std::string const& prop =
445 this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
446 if (prop.empty() || (prop == "AUTO")) {
447 // Autodetect number of CPUs
448 this->AutogenTarget.Parallel = GetParallelCPUCount();
450 this->AutogenTarget.Parallel = 1;
454 // Autogen target info and settings files
457 this->AutogenTarget.InfoFile =
458 cmStrCat(this->Dir.Info, "/AutogenInfo.json");
460 // Used settings file
461 ConfigFileNames(this->AutogenTarget.SettingsFile,
462 cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
463 ConfigFileClean(this->AutogenTarget.SettingsFile);
466 ConfigFileNames(this->AutogenTarget.ParseCacheFile,
467 cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
468 ConfigFileClean(this->AutogenTarget.ParseCacheFile);
471 // Autogen target: Compute user defined dependencies
473 this->AutogenTarget.DependOrigin =
474 this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
476 std::string const& deps =
477 this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
479 for (std::string const& depName : cmExpandedList(deps)) {
480 // Allow target and file dependencies
481 auto* depTarget = this->Makefile->FindTargetToUse(depName);
482 if (depTarget != nullptr) {
483 this->AutogenTarget.DependTargets.insert(depTarget);
485 this->AutogenTarget.DependFiles.insert(depName);
491 if (this->Moc.Enabled) {
493 if (cmIsOn(this->GenTarget->GetSafeProperty("AUTOMOC_PATH_PREFIX"))) {
494 this->Moc.PathPrefix = true;
497 // CMAKE_AUTOMOC_RELAXED_MODE
498 if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
499 this->Moc.RelaxedMode = true;
500 this->Makefile->IssueMessage(
501 MessageType::AUTHOR_WARNING,
502 cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
503 "deprecated an will be removed in the future. Consider "
504 "disabling it and converting the target ",
505 this->GenTarget->GetName(), " to regular mode."));
509 cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
512 cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
513 this->Moc.MacroNames);
515 auto filterList = cmExpandedList(
516 this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
517 if ((filterList.size() % 2) != 0) {
518 cmSystemTools::Error(
519 cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
520 filterList.size(), " is not a multiple of 2."));
523 this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
524 this->Moc.DependFilters.emplace_back(
526 "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
527 "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
528 for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
529 this->Moc.DependFilters.emplace_back(filterList[ii],
536 // Init rcc specific settings
537 if (this->Rcc.Enabled && !InitRcc()) {
541 // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
542 if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
543 this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
547 if (!this->InitScanFiles()) {
551 // Create autogen target
552 if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
556 // Create rcc targets
557 if (this->Rcc.Enabled && !this->InitRccTargets()) {
564 bool cmQtAutoGenInitializer::InitMoc()
566 // Mocs compilation file
567 this->Moc.CompilationFile =
568 cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
571 if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
572 (this->QtVersion >= IntegerVersion(5, 8))) {
574 this->Makefile->GetDefExpandList("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND",
575 this->Moc.PredefsCmd);
577 if (!this->Moc.PredefsCmd.empty()) {
578 ConfigFileNames(this->Moc.PredefsFile,
579 cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
585 SearchPathSanitizer sanitizer(this->Makefile);
587 [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
588 // Get the include dirs for this target, without stripping the implicit
589 // include dirs off, see issue #13667.
590 std::vector<std::string> dirs;
591 bool const appendImplicit = (this->QtVersion.Major >= 5);
592 this->LocalGen->GetIncludeDirectoriesImplicit(
593 dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
594 return sanitizer(dirs);
597 // Default configuration include directories
598 this->Moc.Includes.Default = getDirs(this->ConfigDefault);
599 // Other configuration settings
600 if (this->MultiConfig) {
601 for (std::string const& cfg : this->ConfigsList) {
602 std::vector<std::string> dirs = getDirs(cfg);
603 if (dirs == this->Moc.Includes.Default) {
606 this->Moc.Includes.Config[cfg] = std::move(dirs);
611 // Moc compile definitions
613 auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
614 std::set<std::string> defines;
615 this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
617 if (this->Moc.PredefsCmd.empty()) {
618 // Add WIN32 definition if we don't have a moc_predefs.h
619 defines.insert("WIN32");
625 // Default configuration defines
626 this->Moc.Defines.Default = getDefs(this->ConfigDefault);
627 // Other configuration defines
628 if (this->MultiConfig) {
629 for (std::string const& cfg : this->ConfigsList) {
630 std::set<std::string> defines = getDefs(cfg);
631 if (defines == this->Moc.Defines.Default) {
634 this->Moc.Defines.Config[cfg] = std::move(defines);
641 if (!this->GetQtExecutable(this->Moc, "moc", false)) {
644 // Let the _autogen target depend on the moc executable
645 if (this->Moc.ExecutableTarget != nullptr) {
646 this->AutogenTarget.DependTargets.insert(
647 this->Moc.ExecutableTarget->Target);
654 bool cmQtAutoGenInitializer::InitUic()
658 std::string const& usp =
659 this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
661 this->Uic.SearchPaths =
662 SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
665 // Uic target options
667 auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
668 std::vector<std::string> opts;
669 this->GenTarget->GetAutoUicOptions(opts, cfg);
674 this->Uic.Options.Default = getOpts(this->ConfigDefault);
675 // Configuration specific options
676 if (this->MultiConfig) {
677 for (std::string const& cfg : this->ConfigsList) {
678 std::vector<std::string> options = getOpts(cfg);
679 if (options == this->Uic.Options.Default) {
682 this->Uic.Options.Config[cfg] = std::move(options);
689 if (!this->GetQtExecutable(this->Uic, "uic", true)) {
692 // Let the _autogen target depend on the uic executable
693 if (this->Uic.ExecutableTarget != nullptr) {
694 this->AutogenTarget.DependTargets.insert(
695 this->Uic.ExecutableTarget->Target);
702 bool cmQtAutoGenInitializer::InitRcc()
706 if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
709 // Evaluate test output on demand
710 CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
711 if (!features.Evaluated) {
712 // Look for list options
713 if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
714 if (features.HelpOutput.find("--list") != std::string::npos) {
715 features.ListOptions.emplace_back("--list");
716 } else if (features.HelpOutput.find("-list") != std::string::npos) {
717 features.ListOptions.emplace_back("-list");
720 // Evaluation finished
721 features.Evaluated = true;
728 bool cmQtAutoGenInitializer::InitScanFiles()
730 cmake const* cm = this->Makefile->GetCMakeInstance();
731 auto const& kw = this->GlobalInitializer->kw();
733 auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
734 bool muIt) -> MUFileHandle {
735 MUFileHandle muf = cm::make_unique<MUFile>();
736 muf->FullPath = fullPath;
738 muf->Generated = sf->GetIsGenerated();
739 bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
740 muf->SkipMoc = this->Moc.Enabled &&
741 (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
742 muf->SkipUic = this->Uic.Enabled &&
743 (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
745 muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
746 muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
751 auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
752 cmSourceFile* sf = muf->SF;
753 const bool muIt = (muf->MocIt || muf->UicIt);
754 if (this->CMP0100Accept || (extension != "hh")) {
756 if (muIt && muf->Generated) {
757 this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
759 this->AutogenTarget.Headers.emplace(sf, std::move(muf));
760 } else if (muIt && this->CMP0100Warn) {
761 // Store file for warning message
762 this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
766 auto addMUSource = [this](MUFileHandle&& muf) {
767 if ((muf->MocIt || muf->UicIt) && muf->Generated) {
768 this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
770 this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
773 // Scan through target files
775 // Scan through target files
776 std::vector<cmSourceFile*> srcFiles;
777 this->GenTarget->GetConfigCommonSourceFiles(srcFiles);
778 for (cmSourceFile* sf : srcFiles) {
779 // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
780 // Since we're iterating over source files that might be not in the
781 // target we need to check for path errors (not existing files).
782 std::string pathError;
783 std::string const& fullPath = sf->ResolveFullPath(&pathError);
784 if (!pathError.empty() || fullPath.empty()) {
787 std::string const& extLower =
788 cmSystemTools::LowerCase(sf->GetExtension());
790 // Register files that will be scanned by moc or uic
791 if (this->MocOrUicEnabled()) {
792 if (cm->IsHeaderExtension(extLower)) {
793 addMUHeader(makeMUFile(sf, fullPath, true), extLower);
794 } else if (cm->IsSourceExtension(extLower)) {
795 addMUSource(makeMUFile(sf, fullPath, true));
799 // Register rcc enabled files
800 if (this->Rcc.Enabled) {
801 if ((extLower == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
802 !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
805 qrc.QrcFile = fullPath;
807 cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
808 qrc.Generated = sf->GetIsGenerated();
811 std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
813 cmExpandList(opts, qrc.Options);
816 this->Rcc.Qrcs.push_back(std::move(qrc));
821 // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
822 // sources meta data cache. Clear it so that OBJECT library targets that
823 // are AUTOGEN initialized after this target get their added
824 // mocs_compilation.cpp source acknowledged by this target.
825 this->GenTarget->ClearSourcesCache();
827 // For source files find additional headers and private headers
828 if (this->MocOrUicEnabled()) {
829 // Header search suffixes and extensions
830 static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
831 auto const& exts = cm->GetHeaderExtensions();
832 // Scan through sources
833 for (auto const& pair : this->AutogenTarget.Sources) {
834 MUFile const& muf = *pair.second;
835 if (muf.MocIt || muf.UicIt) {
836 // Search for the default header file and a private header
837 std::string const& srcFullPath = muf.SF->ResolveFullPath();
838 std::string basePath = cmStrCat(
839 cmQtAutoGen::SubDirPrefix(srcFullPath),
840 cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
841 for (auto const& suffix : suffixes) {
842 std::string const suffixedPath = cmStrCat(basePath, suffix);
843 for (auto const& ext : exts) {
844 std::string fullPath = cmStrCat(suffixedPath, '.', ext);
846 auto constexpr locationKind = cmSourceFileLocationKind::Known;
848 this->Makefile->GetSource(fullPath, locationKind);
850 // Check if we know about this header already
851 if (cm::contains(this->AutogenTarget.Headers, sf)) {
854 // We only accept not-GENERATED files that do exist.
855 if (!sf->GetIsGenerated() &&
856 !cmSystemTools::FileExists(fullPath)) {
859 } else if (cmSystemTools::FileExists(fullPath)) {
860 // Create a new source file for the existing file
861 sf = this->Makefile->CreateSource(fullPath, false, locationKind);
865 auto eMuf = makeMUFile(sf, fullPath, true);
866 // Ony process moc/uic when the parent is processed as well
873 addMUHeader(std::move(eMuf), ext);
881 // Scan through all source files in the makefile to extract moc and uic
882 // parameters. Historically we support non target source file parameters.
883 // The reason is that their file names might be discovered from source files
884 // at generation time.
885 if (this->MocOrUicEnabled()) {
886 for (const auto& sf : this->Makefile->GetSourceFiles()) {
887 // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
888 // Since we're iterating over source files that might be not in the
889 // target we need to check for path errors (not existing files).
890 std::string pathError;
891 std::string const& fullPath = sf->ResolveFullPath(&pathError);
892 if (!pathError.empty() || fullPath.empty()) {
895 std::string const& extLower =
896 cmSystemTools::LowerCase(sf->GetExtension());
898 if (cm->IsHeaderExtension(extLower)) {
899 if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
900 auto muf = makeMUFile(sf.get(), fullPath, false);
901 if (muf->SkipMoc || muf->SkipUic) {
902 addMUHeader(std::move(muf), extLower);
905 } else if (cm->IsSourceExtension(extLower)) {
906 if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
907 auto muf = makeMUFile(sf.get(), fullPath, false);
908 if (muf->SkipMoc || muf->SkipUic) {
909 addMUSource(std::move(muf));
912 } else if (this->Uic.Enabled && (extLower == kw.ui)) {
914 bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
916 (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
918 // Check if the .ui file has uic options
919 std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
920 if (!uicOpts.empty()) {
921 this->Uic.UiFiles.emplace_back(fullPath, cmExpandedList(uicOpts));
924 // Register skipped .ui file
925 this->Uic.SkipUi.insert(fullPath);
931 // Process GENERATED sources and headers
932 if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
933 if (this->CMP0071Accept) {
934 // Let the autogen target depend on the GENERATED files
935 for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
936 this->AutogenTarget.DependFiles.insert(muf->FullPath);
938 } else if (this->CMP0071Warn) {
939 cm::string_view property;
940 if (this->Moc.Enabled && this->Uic.Enabled) {
941 property = "SKIP_AUTOGEN";
942 } else if (this->Moc.Enabled) {
943 property = "SKIP_AUTOMOC";
944 } else if (this->Uic.Enabled) {
945 property = "SKIP_AUTOUIC";
948 for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
949 files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
951 this->Makefile->IssueMessage(
952 MessageType::AUTHOR_WARNING,
954 cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
955 "For compatibility, CMake is excluding the GENERATED source "
957 files, "from processing by ",
958 cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
959 ". If any of the files should be processed, set CMP0071 to NEW. "
960 "If any of the files should not be processed, "
961 "explicitly exclude them by setting the source file property ",
962 property, ":\n set_property(SOURCE file.h PROPERTY ", property,
967 // Generate CMP0100 warning
968 if (this->MocOrUicEnabled() &&
969 !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
970 cm::string_view property;
971 if (this->Moc.Enabled && this->Uic.Enabled) {
972 property = "SKIP_AUTOGEN";
973 } else if (this->Moc.Enabled) {
974 property = "SKIP_AUTOMOC";
975 } else if (this->Uic.Enabled) {
976 property = "SKIP_AUTOUIC";
979 for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
980 files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
982 this->Makefile->IssueMessage(
983 MessageType::AUTHOR_WARNING,
985 cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
986 "For compatibility, CMake is excluding the header file(s):\n", files,
987 "from processing by ",
988 cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
989 ". If any of the files should be processed, set CMP0100 to NEW. "
990 "If any of the files should not be processed, "
991 "explicitly exclude them by setting the source file property ",
992 property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
997 if (!this->Rcc.Qrcs.empty()) {
998 const bool modernQt = (this->QtVersion.Major >= 5);
999 // Target rcc options
1000 std::vector<std::string> optionsTarget =
1001 cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
1003 // Check if file name is unique
1004 for (Qrc& qrc : this->Rcc.Qrcs) {
1006 for (Qrc const& qrc2 : this->Rcc.Qrcs) {
1007 if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
1013 // Path checksum and file names
1014 for (Qrc& qrc : this->Rcc.Qrcs) {
1016 qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
1018 qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
1019 "/qrc_", qrc.QrcName, ".cpp");
1020 std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
1021 qrc.QrcName, '_', qrc.QrcPathChecksum);
1022 qrc.LockFile = cmStrCat(base, "_Lock.lock");
1023 qrc.InfoFile = cmStrCat(base, "_Info.json");
1024 ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
1027 for (Qrc& qrc : this->Rcc.Qrcs) {
1029 std::vector<std::string> opts = optionsTarget;
1030 // Merge computed "-name XYZ" option
1032 std::string name = qrc.QrcName;
1033 // Replace '-' with '_'. The former is not valid for symbol names.
1034 std::replace(name.begin(), name.end(), '-', '_');
1036 name += cmStrCat('_', qrc.QrcPathChecksum);
1038 std::vector<std::string> nameOpts;
1039 nameOpts.emplace_back("-name");
1040 nameOpts.emplace_back(std::move(name));
1041 RccMergeOptions(opts, nameOpts, modernQt);
1043 // Merge file option
1044 RccMergeOptions(opts, qrc.Options, modernQt);
1045 qrc.Options = std::move(opts);
1048 for (Qrc& qrc : this->Rcc.Qrcs) {
1049 if (!qrc.Generated) {
1051 RccLister const lister(this->Rcc.Executable,
1052 this->Rcc.ExecutableFeatures->ListOptions);
1053 if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
1054 cmSystemTools::Error(error);
1064 bool cmQtAutoGenInitializer::InitAutogenTarget()
1066 // Register info file as generated by CMake
1067 this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
1069 // Files provided by the autogen target
1070 std::vector<std::string> autogenProvides;
1071 if (this->Moc.Enabled) {
1072 this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
1073 autogenProvides.push_back(this->Moc.CompilationFile);
1076 // Compose target comment
1077 std::string autogenComment;
1080 if (this->Moc.Enabled) {
1083 if (this->Uic.Enabled) {
1084 if (!tools.empty()) {
1089 autogenComment = cmStrCat("Automatic ", tools, " for target ",
1090 this->GenTarget->GetName());
1093 // Compose command lines
1094 // TODO: Refactor autogen to output a per-config mocs_compilation.cpp instead
1095 // of fiddling with the include directories
1096 std::vector<std::string> configs;
1097 this->GlobalGen->GetQtAutoGenConfigs(configs);
1098 bool stdPipesUTF8 = true;
1099 cmCustomCommandLines commandLines;
1100 for (auto const& config : configs) {
1101 commandLines.push_back(cmMakeCommandLine(
1102 { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
1103 this->AutogenTarget.InfoFile, config }));
1106 // Use PRE_BUILD on demand
1107 bool usePRE_BUILD = false;
1108 if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
1109 // Under VS use a PRE_BUILD event instead of a separate target to
1110 // reduce the number of targets loaded into the IDE.
1111 // This also works around a VS 11 bug that may skip updating the target:
1112 // https://connect.microsoft.com/VisualStudio/feedback/details/769495
1113 usePRE_BUILD = true;
1115 // Disable PRE_BUILD in some cases
1117 // Cannot use PRE_BUILD with file depends
1118 if (!this->AutogenTarget.DependFiles.empty()) {
1119 usePRE_BUILD = false;
1121 // Cannot use PRE_BUILD when a global autogen target is in place
1122 if (AutogenTarget.GlobalTarget) {
1123 usePRE_BUILD = false;
1126 // Create the autogen target/command
1128 // Add additional autogen target dependencies to origin target
1129 for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1130 this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
1134 // Add the pre-build command directly to bypass the OBJECT_LIBRARY
1135 // rejection in cmMakefile::AddCustomCommandToTarget because we know
1136 // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
1138 // PRE_BUILD does not support file dependencies!
1139 const std::vector<std::string> no_output;
1140 const std::vector<std::string> no_deps;
1141 cmCustomCommand cc(no_output, autogenProvides, no_deps, commandLines,
1142 this->Makefile->GetBacktrace(), autogenComment.c_str(),
1143 this->Dir.Work.c_str(), stdPipesUTF8);
1144 cc.SetEscapeOldStyle(false);
1145 cc.SetEscapeAllowMakeVars(true);
1146 this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
1149 // Add link library target dependencies to the autogen target
1151 if (this->AutogenTarget.DependOrigin) {
1152 // add_dependencies/addUtility do not support generator expressions.
1153 // We depend only on the libraries found in all configs therefore.
1154 std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
1155 for (std::string const& config : this->ConfigsList) {
1156 cmLinkImplementationLibraries const* libs =
1157 this->GenTarget->GetLinkImplementationLibraries(config);
1158 if (libs != nullptr) {
1159 for (cmLinkItem const& item : libs->Libraries) {
1160 cmGeneratorTarget const* libTarget = item.Target;
1161 if ((libTarget != nullptr) &&
1162 !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
1163 // Increment target config count
1164 commonTargets[libTarget]++;
1169 for (auto const& item : commonTargets) {
1170 if (item.second == this->ConfigsList.size()) {
1171 this->AutogenTarget.DependTargets.insert(item.first->Target);
1176 std::vector<std::string> dependencies(
1177 this->AutogenTarget.DependFiles.begin(),
1178 this->AutogenTarget.DependFiles.end());
1180 const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
1181 this->GlobalGen->GetName().find("Ninja") != std::string::npos;
1182 if (useNinjaDepfile) {
1183 // Create a custom command that generates a timestamp file and
1184 // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
1186 // Also create an additional '_autogen_timestamp_deps' that the custom
1187 // command will depend on. It will have no sources or commands to
1188 // execute, but it will have dependencies that would originally be
1189 // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
1190 // serve as a list of order-only dependencies for the custom command,
1191 // without forcing the custom command to re-execute.
1193 // The dependency tree would then look like
1194 // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
1195 // '_autogen' target.
1196 const auto timestampTargetName =
1197 cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
1198 std::vector<std::string> timestampTargetProvides;
1199 cmCustomCommandLines timestampTargetCommandLines;
1201 // Add additional autogen target dependencies to
1202 // '_autogen_timestamp_deps'.
1203 for (const cmTarget* t : this->AutogenTarget.DependTargets) {
1204 dependencies.push_back(t->GetName());
1207 cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
1208 timestampTargetName, true, this->Dir.Work.c_str(),
1209 /*byproducts=*/timestampTargetProvides,
1210 /*depends=*/dependencies, timestampTargetCommandLines, false, nullptr);
1211 this->LocalGen->AddGeneratorTarget(
1212 cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
1214 // Set FOLDER property on the timestamp target, so it appears in the
1215 // appropriate folder in an IDE or in the file api.
1216 if (!this->TargetsFolder.empty()) {
1217 timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
1220 // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
1221 // moc and uic executables (whichever are enabled).
1222 dependencies.clear();
1223 dependencies.push_back(timestampTargetName);
1225 if (this->Moc.ExecutableTarget != nullptr) {
1226 dependencies.push_back(this->Moc.ExecutableTarget->Target->GetName());
1228 if (this->Uic.ExecutableTarget != nullptr) {
1229 dependencies.push_back(this->Uic.ExecutableTarget->Target->GetName());
1232 // Create the custom command that outputs the timestamp file.
1233 const char timestampFileName[] = "timestamp";
1234 const std::string outputFile =
1235 cmStrCat(this->Dir.Build, "/", timestampFileName);
1236 this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
1237 auto relativeBinaryDir = cmSystemTools::RelativePath(
1238 this->LocalGen->GetBinaryDirectory(),
1239 this->LocalGen->GetCurrentBinaryDirectory());
1240 if (!relativeBinaryDir.empty()) {
1241 relativeBinaryDir = cmStrCat(relativeBinaryDir, "/");
1243 this->AutogenTarget.DepFileRuleName =
1244 cmStrCat(relativeBinaryDir, this->GenTarget->GetName(), "_autogen/",
1246 commandLines.push_back(cmMakeCommandLine(
1247 { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
1249 this->AddGeneratedSource(outputFile, this->Moc);
1250 const std::string no_main_dependency;
1251 this->LocalGen->AddCustomCommandToOutput(
1252 outputFile, dependencies, no_main_dependency, commandLines,
1253 autogenComment.c_str(), this->Dir.Work.c_str(), /*replace=*/false,
1254 /*escapeOldStyle=*/false,
1255 /*uses_terminal=*/false,
1256 /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
1259 // Alter variables for the autogen target which now merely wraps the
1261 dependencies.clear();
1262 dependencies.push_back(outputFile);
1263 commandLines.clear();
1264 autogenComment.clear();
1267 // Create autogen target
1268 cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
1269 this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
1270 /*byproducts=*/autogenProvides,
1271 /*depends=*/dependencies, commandLines, false, autogenComment.c_str());
1272 // Create autogen generator target
1273 this->LocalGen->AddGeneratorTarget(
1274 cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
1276 // Forward origin utilities to autogen target
1277 if (this->AutogenTarget.DependOrigin) {
1278 for (BT<std::pair<std::string, bool>> const& depName :
1279 this->GenTarget->GetUtilities()) {
1280 autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
1283 if (!useNinjaDepfile) {
1284 // Add additional autogen target dependencies to autogen target
1285 for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1286 autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
1290 // Set FOLDER property in autogen target
1291 if (!this->TargetsFolder.empty()) {
1292 autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
1295 // Add autogen target to the origin target dependencies
1296 this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
1299 // Add autogen target to the global autogen target dependencies
1300 if (this->AutogenTarget.GlobalTarget) {
1301 this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
1302 this->AutogenTarget.Name);
1309 bool cmQtAutoGenInitializer::InitRccTargets()
1311 for (Qrc const& qrc : this->Rcc.Qrcs) {
1312 // Register info file as generated by CMake
1313 this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
1314 // Register file at target
1316 cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
1317 sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
1320 std::vector<std::string> ccOutput;
1321 ccOutput.push_back(qrc.OutputFile);
1323 std::vector<std::string> ccDepends;
1324 // Add the .qrc and info file to the custom command dependencies
1325 ccDepends.push_back(qrc.QrcFile);
1326 ccDepends.push_back(qrc.InfoFile);
1328 bool stdPipesUTF8 = true;
1329 cmCustomCommandLines commandLines;
1330 if (this->MultiConfig) {
1331 // Build for all configurations
1332 for (std::string const& config : this->ConfigsList) {
1333 commandLines.push_back(
1334 cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1335 "cmake_autorcc", qrc.InfoFile, config }));
1338 commandLines.push_back(
1339 cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1340 "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
1342 std::string ccComment =
1343 cmStrCat("Automatic RCC for ",
1344 FileProjectRelativePath(this->Makefile, qrc.QrcFile));
1346 if (qrc.Generated || this->Rcc.GlobalTarget) {
1347 // Create custom rcc target
1350 ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
1352 ccName += cmStrCat('_', qrc.QrcPathChecksum);
1355 cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
1356 ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
1357 commandLines, false, ccComment.c_str(), false, false, "",
1360 // Create autogen generator target
1361 this->LocalGen->AddGeneratorTarget(
1362 cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
1364 // Set FOLDER property in autogen target
1365 if (!this->TargetsFolder.empty()) {
1366 autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
1368 if (!this->Rcc.ExecutableTargetName.empty()) {
1369 autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
1373 // Add autogen target to the origin target dependencies
1374 this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
1376 // Add autogen target to the global autogen target dependencies
1377 if (this->Rcc.GlobalTarget) {
1378 this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
1381 // Create custom rcc command
1383 std::vector<std::string> ccByproducts;
1385 // Add the resource files to the dependencies
1386 for (std::string const& fileName : qrc.Resources) {
1387 // Add resource file to the custom command dependencies
1388 ccDepends.push_back(fileName);
1390 if (!this->Rcc.ExecutableTargetName.empty()) {
1391 ccDepends.push_back(this->Rcc.ExecutableTargetName);
1393 std::string no_main_dependency;
1394 cmImplicitDependsList no_implicit_depends;
1395 this->LocalGen->AddCustomCommandToOutput(
1396 ccOutput, ccByproducts, ccDepends, no_main_dependency,
1397 no_implicit_depends, commandLines, ccComment.c_str(),
1398 this->Dir.Work.c_str(), false, true, false, false, "", "",
1401 // Reconfigure when .qrc file changes
1402 this->Makefile->AddCMakeDependFile(qrc.QrcFile);
1409 bool cmQtAutoGenInitializer::SetupCustomTargets()
1411 // Create info directory on demand
1412 if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
1413 cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
1414 Quoted(this->Dir.Info)));
1418 // Generate autogen target info file
1419 if (this->MocOrUicEnabled()) {
1420 // Write autogen target info files
1421 if (!this->SetupWriteAutogenInfo()) {
1426 // Write AUTORCC info files
1427 return !this->Rcc.Enabled || this->SetupWriteRccInfo();
1430 bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
1433 auto MfDef = [this](std::string const& key) {
1434 return this->Makefile->GetSafeDefinition(key);
1437 // Filtered headers and sources
1438 std::set<std::string> moc_skip;
1439 std::set<std::string> uic_skip;
1440 std::vector<MUFile const*> headers;
1441 std::vector<MUFile const*> sources;
1445 headers.reserve(this->AutogenTarget.Headers.size());
1446 for (auto const& pair : this->AutogenTarget.Headers) {
1447 MUFile const* const muf = pair.second.get();
1448 if (muf->Generated && !this->CMP0071Accept) {
1452 moc_skip.insert(muf->FullPath);
1455 uic_skip.insert(muf->FullPath);
1457 if (muf->MocIt || muf->UicIt) {
1458 headers.emplace_back(muf);
1461 std::sort(headers.begin(), headers.end(),
1462 [](MUFile const* a, MUFile const* b) {
1463 return (a->FullPath < b->FullPath);
1469 sources.reserve(this->AutogenTarget.Sources.size());
1470 for (auto const& pair : this->AutogenTarget.Sources) {
1471 MUFile const* const muf = pair.second.get();
1472 if (muf->Generated && !this->CMP0071Accept) {
1476 moc_skip.insert(muf->FullPath);
1479 uic_skip.insert(muf->FullPath);
1481 if (muf->MocIt || muf->UicIt) {
1482 sources.emplace_back(muf);
1485 std::sort(sources.begin(), sources.end(),
1486 [](MUFile const* a, MUFile const* b) {
1487 return (a->FullPath < b->FullPath);
1495 info.SetBool("MULTI_CONFIG", this->MultiConfig);
1496 info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
1497 info.SetUInt("VERBOSITY", this->Verbosity);
1500 info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1501 info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1502 info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1503 info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1504 info.Set("BUILD_DIR", this->Dir.Build);
1505 info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1507 info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
1508 info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
1509 info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
1510 info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
1512 info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
1513 info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
1514 info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
1515 info.Set("DEP_FILE", this->AutogenTarget.DepFile);
1516 info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
1517 info.SetArray("HEADER_EXTENSIONS",
1518 this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
1520 "HEADERS", headers, [this](Json::Value& jval, MUFile const* muf) {
1522 jval[0u] = muf->FullPath;
1523 jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1524 jval[2u] = this->GetMocBuildPath(*muf);
1527 "SOURCES", sources, [](Json::Value& jval, MUFile const* muf) {
1529 jval[0u] = muf->FullPath;
1530 jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1533 // Write moc settings
1534 if (this->Moc.Enabled) {
1535 info.SetArray("MOC_SKIP", moc_skip);
1536 info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
1537 info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
1538 info.SetArray("MOC_OPTIONS", this->Moc.Options);
1539 info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
1540 info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
1541 info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
1543 "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
1544 [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
1546 jval[0u] = pair.first;
1547 jval[1u] = pair.second;
1549 info.Set("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
1550 info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
1551 info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
1554 // Write uic settings
1555 if (this->Uic.Enabled) {
1556 // Add skipped .ui files
1557 uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
1559 info.SetArray("UIC_SKIP", uic_skip);
1560 info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFiles,
1561 [](Json::Value& jval, UicT::UiFileT const& uiFile) {
1563 jval[0u] = uiFile.first;
1564 InfoWriter::MakeStringArray(jval[1u], uiFile.second);
1566 info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
1567 info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
1570 info.Save(this->AutogenTarget.InfoFile);
1575 bool cmQtAutoGenInitializer::SetupWriteRccInfo()
1577 for (Qrc const& qrc : this->Rcc.Qrcs) {
1579 auto MfDef = [this](std::string const& key) {
1580 return this->Makefile->GetSafeDefinition(key);
1586 info.SetBool("MULTI_CONFIG", this->MultiConfig);
1587 info.SetUInt("VERBOSITY", this->Verbosity);
1590 info.Set("LOCK_FILE", qrc.LockFile);
1591 info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
1594 info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1595 info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1596 info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1597 info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1598 info.Set("BUILD_DIR", this->Dir.Build);
1599 info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1602 info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
1603 info.SetArray("RCC_LIST_OPTIONS",
1604 this->Rcc.ExecutableFeatures->ListOptions);
1607 info.Set("SOURCE", qrc.QrcFile);
1608 info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
1609 info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
1610 info.SetArray("OPTIONS", qrc.Options);
1611 info.SetArray("INPUTS", qrc.Resources);
1613 info.Save(qrc.InfoFile);
1619 cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
1620 std::string const& filename)
1622 cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
1623 gFile->SetProperty("GENERATED", "1");
1624 gFile->SetProperty("SKIP_AUTOGEN", "1");
1628 cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
1629 std::string const& filename, GenVarsT const& genVars, bool prepend)
1631 // Register source at makefile
1632 cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
1633 // Add source file to target
1634 this->GenTarget->AddSource(filename, prepend);
1636 // Add source file to source group
1637 this->AddToSourceGroup(filename, genVars.GenNameUpper);
1642 void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
1643 cm::string_view genNameUpper)
1645 cmSourceGroup* sourceGroup = nullptr;
1646 // Acquire source group
1648 std::string property;
1649 std::string groupName;
1651 // Prefer generator specific source group name
1652 std::initializer_list<std::string> const props{
1653 cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
1655 for (std::string const& prop : props) {
1656 cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
1657 if (propName && !propName->empty()) {
1658 groupName = *propName;
1664 // Generate a source group on demand
1665 if (!groupName.empty()) {
1666 sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
1667 if (sourceGroup == nullptr) {
1668 cmSystemTools::Error(
1669 cmStrCat(genNameUpper, " error in ", property,
1670 ": Could not find or create the source group ",
1671 cmQtAutoGen::Quoted(groupName)));
1675 if (sourceGroup != nullptr) {
1676 sourceGroup->AddGroupFile(fileName);
1680 void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
1682 this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
1686 void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
1687 cm::string_view prefix,
1688 cm::string_view suffix)
1690 configString.Default = cmStrCat(prefix, suffix);
1691 if (this->MultiConfig) {
1692 for (auto const& cfg : this->ConfigsList) {
1693 configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
1698 void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
1700 this->AddCleanFile(configString.Default);
1701 if (this->MultiConfig) {
1702 for (auto const& pair : configString.Config) {
1703 this->AddCleanFile(pair.second);
1708 std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
1709 cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
1711 // Converts a char ptr to an unsigned int value
1712 auto toUInt = [](const char* const input) -> unsigned int {
1713 unsigned long tmp = 0;
1714 if (input != nullptr && cmStrToULong(input, &tmp)) {
1715 return static_cast<unsigned int>(tmp);
1719 auto toUInt2 = [](cmProp input) -> unsigned int {
1720 unsigned long tmp = 0;
1721 if (input != nullptr && cmStrToULong(*input, &tmp)) {
1722 return static_cast<unsigned int>(tmp);
1727 // Initialize return value to a default
1728 std::pair<IntegerVersion, unsigned int> res(
1730 toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
1733 // Acquire known Qt versions
1734 std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
1736 // Qt version variable prefixes
1737 static std::initializer_list<
1738 std::pair<cm::string_view, cm::string_view>> const keys{
1739 { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
1740 { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
1741 { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
1744 knownQtVersions.reserve(keys.size() * 2);
1746 // Adds a version to the result (nullptr safe)
1747 auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
1749 cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
1750 if (ver.Major != 0) {
1751 knownQtVersions.emplace_back(ver);
1755 // Read versions from variables
1756 for (auto const& keyPair : keys) {
1757 addVersion(target->Makefile->GetDef(std::string(keyPair.first)),
1758 target->Makefile->GetDef(std::string(keyPair.second)));
1761 // Read versions from directory properties
1762 for (auto const& keyPair : keys) {
1763 addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
1764 target->Makefile->GetProperty(std::string(keyPair.second)));
1768 // Evaluate known Qt versions
1769 if (!knownQtVersions.empty()) {
1770 if (res.second == 0) {
1771 // No specific version was requested by the target:
1772 // Use highest known Qt version.
1773 res.first = knownQtVersions.at(0);
1775 // Pick a version from the known versions:
1776 for (auto it : knownQtVersions) {
1777 if (it.Major == res.second) {
1787 std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
1794 std::string basePath =
1795 cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
1796 FileNameWithoutLastExtension(muf.FullPath));
1798 res = cmStrCat(basePath, ".cpp");
1799 if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1803 // File name already emitted.
1804 // Try appending the header suffix to the base path.
1805 basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
1806 res = cmStrCat(basePath, ".cpp");
1807 if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1811 // File name with header extension already emitted.
1812 // Try adding a number to the base path.
1813 constexpr std::size_t number_begin = 2;
1814 constexpr std::size_t number_end = 256;
1815 for (std::size_t ii = number_begin; ii != number_end; ++ii) {
1816 res = cmStrCat(basePath, '_', ii, ".cpp");
1817 if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1822 // Output file name conflict (unlikely, but still...)
1823 cmSystemTools::Error(
1824 cmStrCat("moc output file name conflict for ", muf.FullPath));
1829 bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
1830 const std::string& executable,
1831 bool ignoreMissingTarget) const
1833 auto print_err = [this, &genVars](std::string const& err) {
1834 cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
1835 this->GenTarget->GetName(), ": ", err));
1838 // Custom executable
1840 std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
1841 std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
1843 // Evaluate generator expression
1845 cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
1846 cmGeneratorExpression ge(lfbt);
1847 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
1848 genVars.Executable = cge->Evaluate(this->LocalGen, "");
1850 if (genVars.Executable.empty() && !ignoreMissingTarget) {
1851 print_err(prop + " evaluates to an empty value");
1855 // Create empty compiler features.
1856 genVars.ExecutableFeatures =
1857 std::make_shared<cmQtAutoGen::CompilerFeatures>();
1862 // Find executable target
1864 // Find executable target name
1865 cm::string_view prefix;
1866 if (this->QtVersion.Major == 4) {
1868 } else if (this->QtVersion.Major == 5) {
1870 } else if (this->QtVersion.Major == 6) {
1873 std::string const targetName = cmStrCat(prefix, executable);
1876 cmGeneratorTarget* genTarget =
1877 this->LocalGen->FindGeneratorTargetToUse(targetName);
1878 if (genTarget != nullptr) {
1879 genVars.ExecutableTargetName = targetName;
1880 genVars.ExecutableTarget = genTarget;
1881 if (genTarget->IsImported()) {
1882 genVars.Executable = genTarget->ImportedGetLocation("");
1884 genVars.Executable = genTarget->GetLocation("");
1887 if (ignoreMissingTarget) {
1888 // Create empty compiler features.
1889 genVars.ExecutableFeatures =
1890 std::make_shared<cmQtAutoGen::CompilerFeatures>();
1893 print_err(cmStrCat("Could not find ", executable, " executable target ",
1899 // Get executable features
1902 genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
1903 executable, genVars.Executable, err);
1904 if (!genVars.ExecutableFeatures) {