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>
20 #include "cmsys/SystemInformation.hxx"
22 #include "cm_jsoncpp_value.h"
23 #include "cm_jsoncpp_writer.h"
25 #include "cmAlgorithms.h"
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 "cmQtAutoGen.h"
39 #include "cmQtAutoGenGlobalInitializer.h"
40 #include "cmSourceFile.h"
41 #include "cmSourceFileLocationKind.h"
42 #include "cmSourceGroup.h"
44 #include "cmStateTypes.h"
45 #include "cmStringAlgorithms.h"
46 #include "cmSystemTools.h"
52 unsigned int GetParallelCPUCount()
54 static unsigned int count = 0;
55 // Detect only on the first call
57 cmsys::SystemInformation info;
60 cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
65 std::string FileProjectRelativePath(cmMakefile* makefile,
66 std::string const& fileName)
70 std::string pSource = cmSystemTools::RelativePath(
71 makefile->GetCurrentSourceDirectory(), fileName);
72 std::string pBinary = cmSystemTools::RelativePath(
73 makefile->GetCurrentBinaryDirectory(), fileName);
74 if (pSource.size() < pBinary.size()) {
75 res = std::move(pSource);
76 } else if (pBinary.size() < fileName.size()) {
77 res = std::move(pBinary);
86 * Tests if targetDepend is a STATIC_LIBRARY and if any of its
87 * recursive STATIC_LIBRARY dependencies depends on targetOrigin
88 * (STATIC_LIBRARY cycle).
90 bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
91 cmGeneratorTarget const* targetDepend,
92 std::string const& config)
95 if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
96 (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
97 std::set<cmGeneratorTarget const*> knownLibs;
98 std::deque<cmGeneratorTarget const*> testLibs;
100 // Insert initial static_library dependency
101 knownLibs.insert(targetDepend);
102 testLibs.push_back(targetDepend);
104 while (!testLibs.empty()) {
105 cmGeneratorTarget const* testTarget = testLibs.front();
106 testLibs.pop_front();
107 // Check if the test target is the origin target (cycle)
108 if (testTarget == targetOrigin) {
112 // Collect all static_library dependencies from the test target
113 cmLinkImplementationLibraries const* libs =
114 testTarget->GetLinkImplementationLibraries(config);
115 if (libs != nullptr) {
116 for (cmLinkItem const& item : libs->Libraries) {
117 cmGeneratorTarget const* depTarget = item.Target;
118 if ((depTarget != nullptr) &&
119 (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
120 knownLibs.insert(depTarget).second) {
121 testLibs.push_back(depTarget);
130 /** Sanitizes file search paths. */
131 class SearchPathSanitizer
134 SearchPathSanitizer(cmMakefile* makefile)
135 : SourcePath_(makefile->GetCurrentSourceDirectory())
138 std::vector<std::string> operator()(
139 std::vector<std::string> const& paths) const;
142 std::string SourcePath_;
145 std::vector<std::string> SearchPathSanitizer::operator()(
146 std::vector<std::string> const& paths) const
148 std::vector<std::string> res;
149 res.reserve(paths.size());
150 for (std::string const& srcPath : paths) {
151 // Collapse relative paths
152 std::string path = cmSystemTools::CollapseFullPath(srcPath, SourcePath_);
153 // Remove suffix slashes
154 while (cmHasSuffix(path, '/')) {
157 // Accept only non empty paths
159 res.emplace_back(std::move(path));
165 /** @brief Writes a CMake info file. */
170 void Set(std::string const& key, std::string const& value)
174 void SetConfig(std::string const& key,
175 cmQtAutoGenInitializer::ConfigString const& cfgStr);
176 void SetBool(std::string const& key, bool value) { Value_[key] = value; }
177 void SetUInt(std::string const& key, unsigned int value)
183 template <typename CONT>
184 static bool MakeArray(Json::Value& jval, CONT const& container);
186 template <typename CONT>
187 static void MakeStringArray(Json::Value& jval, CONT const& container);
190 template <typename CONT>
191 void SetArray(std::string const& key, CONT const& container);
192 template <typename CONT>
194 std::string const& key,
195 cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
197 // -- Array of arrays
198 template <typename CONT, typename FUNC>
199 void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
201 // -- Save to json file
202 bool Save(std::string const& filename);
208 void InfoWriter::SetConfig(std::string const& key,
209 cmQtAutoGenInitializer::ConfigString const& cfgStr)
211 Set(key, cfgStr.Default);
212 for (auto const& item : cfgStr.Config) {
213 Set(cmStrCat(key, '_', item.first), item.second);
217 template <typename CONT>
218 bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
220 jval = Json::arrayValue;
221 std::size_t const listSize = cm::size(container);
225 jval.resize(static_cast<unsigned int>(listSize));
229 template <typename CONT>
230 void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
232 if (MakeArray(jval, container)) {
233 Json::ArrayIndex ii = 0;
234 for (std::string const& item : container) {
240 template <typename CONT>
241 void InfoWriter::SetArray(std::string const& key, CONT const& container)
243 MakeStringArray(Value_[key], container);
246 template <typename CONT, typename FUNC>
247 void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
250 Json::Value& jval = Value_[key];
251 if (MakeArray(jval, container)) {
252 Json::ArrayIndex ii = 0;
253 for (auto const& citem : container) {
254 Json::Value& aval = jval[ii++];
255 aval = Json::arrayValue;
261 template <typename CONT>
262 void InfoWriter::SetConfigArray(
263 std::string const& key,
264 cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
266 SetArray(key, cfgStr.Default);
267 for (auto const& item : cfgStr.Config) {
268 SetArray(cmStrCat(key, '_', item.first), item.second);
272 bool InfoWriter::Save(std::string const& filename)
274 cmGeneratedFileStream fileStream;
275 fileStream.SetCopyIfDifferent(true);
276 fileStream.Open(filename, false, true);
281 Json::StyledStreamWriter jsonWriter;
283 jsonWriter.write(fileStream, Value_);
288 return fileStream.Close();
291 } // End of unnamed namespace
293 cmQtAutoGenInitializer::cmQtAutoGenInitializer(
294 cmQtAutoGenGlobalInitializer* globalInitializer,
295 cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
296 bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
297 bool globalAutoRccTarget)
298 : GlobalInitializer(globalInitializer)
299 , GenTarget(genTarget)
300 , GlobalGen(genTarget->GetGlobalGenerator())
301 , LocalGen(genTarget->GetLocalGenerator())
302 , Makefile(genTarget->Makefile)
303 , PathCheckSum(genTarget->Makefile)
304 , QtVersion(qtVersion)
306 AutogenTarget.GlobalTarget = globalAutogenTarget;
307 Moc.Enabled = mocEnabled;
308 Uic.Enabled = uicEnabled;
309 Rcc.Enabled = rccEnabled;
310 Rcc.GlobalTarget = globalAutoRccTarget;
313 bool cmQtAutoGenInitializer::InitCustomTargets()
316 this->MultiConfig = this->GlobalGen->IsMultiConfig();
317 this->ConfigDefault = this->Makefile->GetConfigurations(this->ConfigsList);
318 if (this->ConfigsList.empty()) {
319 this->ConfigsList.push_back(this->ConfigDefault);
325 this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
327 unsigned long iVerb = 0;
328 if (cmStrToULong(def, &iVerb)) {
330 this->Verbosity = static_cast<unsigned int>(iVerb);
332 // Non numeric verbosity
343 this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
344 if (folder == nullptr) {
345 folder = this->Makefile->GetState()->GetGlobalProperty(
346 "AUTOGEN_TARGETS_FOLDER");
348 // Inherit FOLDER property from target (#13688)
349 if (folder == nullptr) {
350 folder = this->GenTarget->GetProperty("FOLDER");
352 if (folder != nullptr) {
353 this->TargetsFolder = folder;
357 // Check status of policy CMP0071 regarding handling of GENERATED files
358 switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
359 case cmPolicies::WARN:
360 // Ignore GENERATED files but warn
361 this->CMP0071Warn = true;
363 case cmPolicies::OLD:
364 // Ignore GENERATED files
366 case cmPolicies::REQUIRED_IF_USED:
367 case cmPolicies::REQUIRED_ALWAYS:
368 case cmPolicies::NEW:
369 // Process GENERATED files
370 this->CMP0071Accept = true;
374 // Check status of policy CMP0100 regarding handling of .hh headers
375 switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
376 case cmPolicies::WARN:
377 // Ignore but .hh files but warn
378 this->CMP0100Warn = true;
380 case cmPolicies::OLD:
383 case cmPolicies::REQUIRED_IF_USED:
384 case cmPolicies::REQUIRED_ALWAYS:
385 case cmPolicies::NEW:
387 this->CMP0100Accept = true;
391 // Common directories
393 // Collapsed current binary directory
394 std::string const cbd = cmSystemTools::CollapseFullPath(
395 std::string(), this->Makefile->GetCurrentBinaryDirectory());
398 this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
400 cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
403 this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
404 if (this->Dir.Build.empty()) {
406 cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
408 cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
409 // Cleanup build directory
410 this->AddCleanFile(this->Dir.Build);
413 this->Dir.Work = cbd;
414 cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
417 ConfigFileNames(this->Dir.Include, cmStrCat(this->Dir.Build, "/include"),
419 this->Dir.IncludeGenExp = this->Dir.Include.Default;
420 if (this->MultiConfig) {
421 this->Dir.IncludeGenExp += "_$<CONFIG>";
425 // Moc, Uic and _autogen target settings
426 if (this->MocOrUicEnabled()) {
427 // Init moc specific settings
428 if (this->Moc.Enabled && !InitMoc()) {
432 // Init uic specific settings
433 if (this->Uic.Enabled && !InitUic()) {
437 // Autogen target name
438 this->AutogenTarget.Name =
439 cmStrCat(this->GenTarget->GetName(), "_autogen");
441 // Autogen target parallel processing
443 std::string prop = this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
444 if (prop.empty() || (prop == "AUTO")) {
445 // Autodetect number of CPUs
446 this->AutogenTarget.Parallel = GetParallelCPUCount();
448 this->AutogenTarget.Parallel = 1;
452 // Autogen target info and settings files
455 this->AutogenTarget.InfoFile =
456 cmStrCat(this->Dir.Info, "/AutogenInfo.json");
458 // Used settings file
459 ConfigFileNames(this->AutogenTarget.SettingsFile,
460 cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
461 ConfigFileClean(this->AutogenTarget.SettingsFile);
464 ConfigFileNames(this->AutogenTarget.ParseCacheFile,
465 cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
466 ConfigFileClean(this->AutogenTarget.ParseCacheFile);
469 // Autogen target: Compute user defined dependencies
471 this->AutogenTarget.DependOrigin =
472 this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
474 std::string const deps =
475 this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
477 for (std::string const& depName : cmExpandedList(deps)) {
478 // Allow target and file dependencies
479 auto* depTarget = this->Makefile->FindTargetToUse(depName);
480 if (depTarget != nullptr) {
481 this->AutogenTarget.DependTargets.insert(depTarget);
483 this->AutogenTarget.DependFiles.insert(depName);
489 if (this->Moc.Enabled) {
491 if (cmIsOn(this->GenTarget->GetSafeProperty("AUTOMOC_PATH_PREFIX"))) {
492 this->Moc.PathPrefix = true;
495 // CMAKE_AUTOMOC_RELAXED_MODE
496 if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
497 this->Moc.RelaxedMode = true;
498 this->Makefile->IssueMessage(
499 MessageType::AUTHOR_WARNING,
500 cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
501 "deprecated an will be removed in the future. Consider "
502 "disabling it and converting the target ",
503 this->GenTarget->GetName(), " to regular mode."));
507 cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
510 cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
511 this->Moc.MacroNames);
513 auto filterList = cmExpandedList(
514 this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
515 if ((filterList.size() % 2) != 0) {
516 cmSystemTools::Error(
517 cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
518 filterList.size(), " is not a multiple of 2."));
521 this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
522 this->Moc.DependFilters.emplace_back(
524 "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
525 "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
526 for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
527 this->Moc.DependFilters.emplace_back(filterList[ii],
534 // Init rcc specific settings
535 if (this->Rcc.Enabled && !InitRcc()) {
539 // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
540 if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
541 this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
545 if (!this->InitScanFiles()) {
549 // Create autogen target
550 if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
554 // Create rcc targets
555 if (this->Rcc.Enabled && !this->InitRccTargets()) {
562 bool cmQtAutoGenInitializer::InitMoc()
564 // Mocs compilation file
565 this->Moc.CompilationFile =
566 cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
569 if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
570 (this->QtVersion >= IntegerVersion(5, 8))) {
572 cmExpandList(this->Makefile->GetSafeDefinition(
573 "CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"),
574 this->Moc.PredefsCmd);
576 if (!this->Moc.PredefsCmd.empty()) {
577 ConfigFileNames(this->Moc.PredefsFile,
578 cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
584 SearchPathSanitizer sanitizer(this->Makefile);
586 [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
587 // Get the include dirs for this target, without stripping the implicit
588 // include dirs off, see issue #13667.
589 std::vector<std::string> dirs;
590 bool const appendImplicit = (this->QtVersion.Major >= 5);
591 this->LocalGen->GetIncludeDirectoriesImplicit(
592 dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
593 return sanitizer(dirs);
596 // Default configuration include directories
597 this->Moc.Includes.Default = getDirs(this->ConfigDefault);
598 // Other configuration settings
599 if (this->MultiConfig) {
600 for (std::string const& cfg : this->ConfigsList) {
601 std::vector<std::string> dirs = getDirs(cfg);
602 if (dirs == this->Moc.Includes.Default) {
605 this->Moc.Includes.Config[cfg] = std::move(dirs);
610 // Moc compile definitions
612 auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
613 std::set<std::string> defines;
614 this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
616 if (this->Moc.PredefsCmd.empty()) {
617 // Add WIN32 definition if we don't have a moc_predefs.h
618 defines.insert("WIN32");
624 // Default configuration defines
625 this->Moc.Defines.Default = getDefs(this->ConfigDefault);
626 // Other configuration defines
627 if (this->MultiConfig) {
628 for (std::string const& cfg : this->ConfigsList) {
629 std::set<std::string> defines = getDefs(cfg);
630 if (defines == this->Moc.Defines.Default) {
633 this->Moc.Defines.Config[cfg] = std::move(defines);
640 if (!this->GetQtExecutable(this->Moc, "moc", false)) {
643 // Let the _autogen target depend on the moc executable
644 if (this->Moc.ExecutableTarget != nullptr) {
645 this->AutogenTarget.DependTargets.insert(
646 this->Moc.ExecutableTarget->Target);
653 bool cmQtAutoGenInitializer::InitUic()
657 std::string const usp =
658 this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
660 this->Uic.SearchPaths =
661 SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
664 // Uic target options
666 auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
667 std::vector<std::string> opts;
668 this->GenTarget->GetAutoUicOptions(opts, cfg);
673 this->Uic.Options.Default = getOpts(this->ConfigDefault);
674 // Configuration specific options
675 if (this->MultiConfig) {
676 for (std::string const& cfg : this->ConfigsList) {
677 std::vector<std::string> options = getOpts(cfg);
678 if (options == this->Uic.Options.Default) {
681 this->Uic.Options.Config[cfg] = std::move(options);
688 if (!this->GetQtExecutable(this->Uic, "uic", true)) {
691 // Let the _autogen target depend on the uic executable
692 if (this->Uic.ExecutableTarget != nullptr) {
693 this->AutogenTarget.DependTargets.insert(
694 this->Uic.ExecutableTarget->Target);
701 bool cmQtAutoGenInitializer::InitRcc()
705 if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
708 // Evaluate test output on demand
709 CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
710 if (!features.Evaluated) {
711 // Look for list options
712 if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
713 if (features.HelpOutput.find("--list") != std::string::npos) {
714 features.ListOptions.emplace_back("--list");
715 } else if (features.HelpOutput.find("-list") != std::string::npos) {
716 features.ListOptions.emplace_back("-list");
719 // Evaluation finished
720 features.Evaluated = true;
727 bool cmQtAutoGenInitializer::InitScanFiles()
729 cmake const* cm = this->Makefile->GetCMakeInstance();
730 auto const& kw = this->GlobalInitializer->kw();
732 auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
733 bool muIt) -> MUFileHandle {
734 MUFileHandle muf = cm::make_unique<MUFile>();
735 muf->FullPath = fullPath;
737 muf->Generated = sf->GetIsGenerated();
738 bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
739 muf->SkipMoc = this->Moc.Enabled &&
740 (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
741 muf->SkipUic = this->Uic.Enabled &&
742 (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
744 muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
745 muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
750 auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
751 cmSourceFile* sf = muf->SF;
752 const bool muIt = (muf->MocIt || muf->UicIt);
753 if (this->CMP0100Accept || (extension != "hh")) {
755 if (muIt && muf->Generated) {
756 this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
758 this->AutogenTarget.Headers.emplace(sf, std::move(muf));
759 } else if (muIt && this->CMP0100Warn) {
760 // Store file for warning message
761 this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
765 auto addMUSource = [this](MUFileHandle&& muf) {
766 if ((muf->MocIt || muf->UicIt) && muf->Generated) {
767 this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
769 this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
772 // Scan through target files
774 // Scan through target files
775 std::vector<cmSourceFile*> srcFiles;
776 this->GenTarget->GetConfigCommonSourceFiles(srcFiles);
777 for (cmSourceFile* sf : srcFiles) {
778 // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
779 // Since we're iterating over source files that might be not in the
780 // target we need to check for path errors (not existing files).
781 std::string pathError;
782 std::string const& fullPath = sf->ResolveFullPath(&pathError);
783 if (!pathError.empty() || fullPath.empty()) {
786 std::string const& extLower =
787 cmSystemTools::LowerCase(sf->GetExtension());
789 // Register files that will be scanned by moc or uic
790 if (this->MocOrUicEnabled()) {
791 if (cm->IsHeaderExtension(extLower)) {
792 addMUHeader(makeMUFile(sf, fullPath, true), extLower);
793 } else if (cm->IsSourceExtension(extLower)) {
794 addMUSource(makeMUFile(sf, fullPath, true));
798 // Register rcc enabled files
799 if (this->Rcc.Enabled) {
800 if ((extLower == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
801 !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
804 qrc.QrcFile = fullPath;
806 cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
807 qrc.Generated = sf->GetIsGenerated();
810 std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
812 cmExpandList(opts, qrc.Options);
815 this->Rcc.Qrcs.push_back(std::move(qrc));
820 // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
821 // sources meta data cache. Clear it so that OBJECT library targets that
822 // are AUTOGEN initialized after this target get their added
823 // mocs_compilation.cpp source acknowledged by this target.
824 this->GenTarget->ClearSourcesCache();
826 // For source files find additional headers and private headers
827 if (this->MocOrUicEnabled()) {
828 // Header search suffixes and extensions
829 static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
830 auto const& exts = cm->GetHeaderExtensions();
831 // Scan through sources
832 for (auto const& pair : this->AutogenTarget.Sources) {
833 MUFile const& muf = *pair.second;
834 if (muf.MocIt || muf.UicIt) {
835 // Search for the default header file and a private header
836 std::string const& srcFullPath = muf.SF->ResolveFullPath();
837 std::string basePath = cmStrCat(
838 cmQtAutoGen::SubDirPrefix(srcFullPath),
839 cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
840 for (auto const& suffix : suffixes) {
841 std::string const suffixedPath = cmStrCat(basePath, suffix);
842 for (auto const& ext : exts) {
843 std::string fullPath = cmStrCat(suffixedPath, '.', ext);
845 auto constexpr locationKind = cmSourceFileLocationKind::Known;
847 this->Makefile->GetSource(fullPath, locationKind);
849 // Check if we know about this header already
850 if (cmContains(this->AutogenTarget.Headers, sf)) {
853 // We only accept not-GENERATED files that do exist.
854 if (!sf->GetIsGenerated() &&
855 !cmSystemTools::FileExists(fullPath)) {
858 } else if (cmSystemTools::FileExists(fullPath)) {
859 // Create a new source file for the existing file
860 sf = this->Makefile->CreateSource(fullPath, false, locationKind);
864 auto eMuf = makeMUFile(sf, fullPath, true);
865 // Ony process moc/uic when the parent is processed as well
872 addMUHeader(std::move(eMuf), ext);
880 // Scan through all source files in the makefile to extract moc and uic
881 // parameters. Historically we support non target source file parameters.
882 // The reason is that their file names might be discovered from source files
883 // at generation time.
884 if (this->MocOrUicEnabled()) {
885 for (const auto& sf : this->Makefile->GetSourceFiles()) {
886 // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
887 // Since we're iterating over source files that might be not in the
888 // target we need to check for path errors (not existing files).
889 std::string pathError;
890 std::string const& fullPath = sf->ResolveFullPath(&pathError);
891 if (!pathError.empty() || fullPath.empty()) {
894 std::string const& extLower =
895 cmSystemTools::LowerCase(sf->GetExtension());
897 if (cm->IsHeaderExtension(extLower)) {
898 if (!cmContains(this->AutogenTarget.Headers, sf.get())) {
899 auto muf = makeMUFile(sf.get(), fullPath, false);
900 if (muf->SkipMoc || muf->SkipUic) {
901 addMUHeader(std::move(muf), extLower);
904 } else if (cm->IsSourceExtension(extLower)) {
905 if (!cmContains(this->AutogenTarget.Sources, sf.get())) {
906 auto muf = makeMUFile(sf.get(), fullPath, false);
907 if (muf->SkipMoc || muf->SkipUic) {
908 addMUSource(std::move(muf));
911 } else if (this->Uic.Enabled && (extLower == kw.ui)) {
913 bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
915 (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
917 // Check if the .ui file has uic options
918 std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
919 if (!uicOpts.empty()) {
920 this->Uic.UiFiles.emplace_back(fullPath, cmExpandedList(uicOpts));
923 // Register skipped .ui file
924 this->Uic.SkipUi.insert(fullPath);
930 // Process GENERATED sources and headers
931 if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
932 if (this->CMP0071Accept) {
933 // Let the autogen target depend on the GENERATED files
934 for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
935 this->AutogenTarget.DependFiles.insert(muf->FullPath);
937 } else if (this->CMP0071Warn) {
938 cm::string_view property;
939 if (this->Moc.Enabled && this->Uic.Enabled) {
940 property = "SKIP_AUTOGEN";
941 } else if (this->Moc.Enabled) {
942 property = "SKIP_AUTOMOC";
943 } else if (this->Uic.Enabled) {
944 property = "SKIP_AUTOUIC";
947 for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
948 files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
950 this->Makefile->IssueMessage(
951 MessageType::AUTHOR_WARNING,
953 cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
954 "For compatibility, CMake is excluding the GENERATED source "
956 files, "from processing by ",
957 cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
958 ". If any of the files should be processed, set CMP0071 to NEW. "
959 "If any of the files should not be processed, "
960 "explicitly exclude them by setting the source file property ",
961 property, ":\n set_property(SOURCE file.h PROPERTY ", property,
966 // Generate CMP0100 warning
967 if (this->MocOrUicEnabled() &&
968 !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
969 cm::string_view property;
970 if (this->Moc.Enabled && this->Uic.Enabled) {
971 property = "SKIP_AUTOGEN";
972 } else if (this->Moc.Enabled) {
973 property = "SKIP_AUTOMOC";
974 } else if (this->Uic.Enabled) {
975 property = "SKIP_AUTOUIC";
978 for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
979 files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
981 this->Makefile->IssueMessage(
982 MessageType::AUTHOR_WARNING,
984 cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
985 "For compatibility, CMake is excluding the header file(s):\n", files,
986 "from processing by ",
987 cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
988 ". If any of the files should be processed, set CMP0100 to NEW. "
989 "If any of the files should not be processed, "
990 "explicitly exclude them by setting the source file property ",
991 property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
996 if (!this->Rcc.Qrcs.empty()) {
997 const bool modernQt = (this->QtVersion.Major >= 5);
998 // Target rcc options
999 std::vector<std::string> optionsTarget =
1000 cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
1002 // Check if file name is unique
1003 for (Qrc& qrc : this->Rcc.Qrcs) {
1005 for (Qrc const& qrc2 : this->Rcc.Qrcs) {
1006 if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
1012 // Path checksum and file names
1013 for (Qrc& qrc : this->Rcc.Qrcs) {
1015 qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
1017 qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
1018 "/qrc_", qrc.QrcName, ".cpp");
1019 std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
1020 qrc.QrcName, '_', qrc.QrcPathChecksum);
1021 qrc.LockFile = cmStrCat(base, "_Lock.lock");
1022 qrc.InfoFile = cmStrCat(base, "_Info.json");
1023 ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
1026 for (Qrc& qrc : this->Rcc.Qrcs) {
1028 std::vector<std::string> opts = optionsTarget;
1029 // Merge computed "-name XYZ" option
1031 std::string name = qrc.QrcName;
1032 // Replace '-' with '_'. The former is not valid for symbol names.
1033 std::replace(name.begin(), name.end(), '-', '_');
1035 name += cmStrCat('_', qrc.QrcPathChecksum);
1037 std::vector<std::string> nameOpts;
1038 nameOpts.emplace_back("-name");
1039 nameOpts.emplace_back(std::move(name));
1040 RccMergeOptions(opts, nameOpts, modernQt);
1042 // Merge file option
1043 RccMergeOptions(opts, qrc.Options, modernQt);
1044 qrc.Options = std::move(opts);
1047 for (Qrc& qrc : this->Rcc.Qrcs) {
1048 if (!qrc.Generated) {
1050 RccLister const lister(this->Rcc.Executable,
1051 this->Rcc.ExecutableFeatures->ListOptions);
1052 if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
1053 cmSystemTools::Error(error);
1063 bool cmQtAutoGenInitializer::InitAutogenTarget()
1065 // Register info file as generated by CMake
1066 this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
1068 // Files provided by the autogen target
1069 std::vector<std::string> autogenProvides;
1070 if (this->Moc.Enabled) {
1071 this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
1072 autogenProvides.push_back(this->Moc.CompilationFile);
1075 // Compose target comment
1076 std::string autogenComment;
1079 if (this->Moc.Enabled) {
1082 if (this->Uic.Enabled) {
1083 if (!tools.empty()) {
1088 autogenComment = cmStrCat("Automatic ", tools, " for target ",
1089 this->GenTarget->GetName());
1092 // Compose command lines
1093 // TODO: Refactor autogen to output a per-config mocs_compilation.cpp instead
1094 // of fiddling with the include directories
1095 std::vector<std::string> configs;
1096 this->GlobalGen->GetQtAutoGenConfigs(configs);
1097 cmCustomCommandLines commandLines;
1098 for (auto const& config : configs) {
1099 commandLines.push_back(cmMakeCommandLine(
1100 { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
1101 this->AutogenTarget.InfoFile, config }));
1104 // Use PRE_BUILD on demand
1105 bool usePRE_BUILD = false;
1106 if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
1107 // Under VS use a PRE_BUILD event instead of a separate target to
1108 // reduce the number of targets loaded into the IDE.
1109 // This also works around a VS 11 bug that may skip updating the target:
1110 // https://connect.microsoft.com/VisualStudio/feedback/details/769495
1111 usePRE_BUILD = true;
1113 // Disable PRE_BUILD in some cases
1115 // Cannot use PRE_BUILD with file depends
1116 if (!this->AutogenTarget.DependFiles.empty()) {
1117 usePRE_BUILD = false;
1119 // Cannot use PRE_BUILD when a global autogen target is in place
1120 if (AutogenTarget.GlobalTarget) {
1121 usePRE_BUILD = false;
1124 // Create the autogen target/command
1126 // Add additional autogen target dependencies to origin target
1127 for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1128 this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
1132 // Add the pre-build command directly to bypass the OBJECT_LIBRARY
1133 // rejection in cmMakefile::AddCustomCommandToTarget because we know
1134 // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
1136 // PRE_BUILD does not support file dependencies!
1137 const std::vector<std::string> no_output;
1138 const std::vector<std::string> no_deps;
1139 cmCustomCommand cc(no_output, autogenProvides, no_deps, commandLines,
1140 this->Makefile->GetBacktrace(), autogenComment.c_str(),
1141 this->Dir.Work.c_str());
1142 cc.SetEscapeOldStyle(false);
1143 cc.SetEscapeAllowMakeVars(true);
1144 this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
1147 // Add link library target dependencies to the autogen target
1149 if (this->AutogenTarget.DependOrigin) {
1150 // add_dependencies/addUtility do not support generator expressions.
1151 // We depend only on the libraries found in all configs therefore.
1152 std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
1153 for (std::string const& config : this->ConfigsList) {
1154 cmLinkImplementationLibraries const* libs =
1155 this->GenTarget->GetLinkImplementationLibraries(config);
1156 if (libs != nullptr) {
1157 for (cmLinkItem const& item : libs->Libraries) {
1158 cmGeneratorTarget const* libTarget = item.Target;
1159 if ((libTarget != nullptr) &&
1160 !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
1161 // Increment target config count
1162 commonTargets[libTarget]++;
1167 for (auto const& item : commonTargets) {
1168 if (item.second == this->ConfigsList.size()) {
1169 this->AutogenTarget.DependTargets.insert(item.first->Target);
1174 std::vector<std::string> dependencies(
1175 this->AutogenTarget.DependFiles.begin(),
1176 this->AutogenTarget.DependFiles.end());
1178 const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
1179 this->GlobalGen->GetName().find("Ninja") != std::string::npos;
1180 if (useNinjaDepfile) {
1181 // Create a custom command that generates a timestamp file and
1182 // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
1184 // Also create an additional '_autogen_timestamp_deps' that the custom
1185 // command will depend on. It will have no sources or commands to
1186 // execute, but it will have dependencies that would originally be
1187 // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
1188 // serve as a list of order-only dependencies for the custom command,
1189 // without forcing the custom command to re-execute.
1191 // The dependency tree would then look like
1192 // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
1193 // '_autogen' target.
1194 const auto timestampTargetName =
1195 cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
1196 std::vector<std::string> timestampTargetProvides;
1197 cmCustomCommandLines timestampTargetCommandLines;
1199 // Add additional autogen target dependencies to
1200 // '_autogen_timestamp_deps'.
1201 for (const cmTarget* t : this->AutogenTarget.DependTargets) {
1202 dependencies.push_back(t->GetName());
1205 cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
1206 timestampTargetName, true, this->Dir.Work.c_str(),
1207 /*byproducts=*/timestampTargetProvides,
1208 /*depends=*/dependencies, timestampTargetCommandLines, false, nullptr);
1209 this->LocalGen->AddGeneratorTarget(
1210 cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
1212 // Set FOLDER property on the timestamp target, so it appears in the
1213 // appropriate folder in an IDE or in the file api.
1214 if (!this->TargetsFolder.empty()) {
1215 timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
1218 // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
1219 // moc and uic executables (whichever are enabled).
1220 dependencies.clear();
1221 dependencies.push_back(timestampTargetName);
1223 if (this->Moc.ExecutableTarget != nullptr) {
1224 dependencies.push_back(this->Moc.ExecutableTarget->Target->GetName());
1226 if (this->Uic.ExecutableTarget != nullptr) {
1227 dependencies.push_back(this->Uic.ExecutableTarget->Target->GetName());
1230 // Create the custom command that outputs the timestamp file.
1231 const char timestampFileName[] = "timestamp";
1232 const std::string outputFile =
1233 cmStrCat(this->Dir.Build, "/", timestampFileName);
1234 this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
1235 auto relativeBinaryDir = cmSystemTools::RelativePath(
1236 this->LocalGen->GetBinaryDirectory(),
1237 this->LocalGen->GetCurrentBinaryDirectory());
1238 if (!relativeBinaryDir.empty()) {
1239 relativeBinaryDir = cmStrCat(relativeBinaryDir, "/");
1241 this->AutogenTarget.DepFileRuleName =
1242 cmStrCat(relativeBinaryDir, this->GenTarget->GetName(), "_autogen/",
1244 commandLines.push_back(cmMakeCommandLine(
1245 { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
1247 this->AddGeneratedSource(outputFile, this->Moc);
1248 const std::string no_main_dependency;
1249 this->LocalGen->AddCustomCommandToOutput(
1250 outputFile, dependencies, no_main_dependency, commandLines,
1251 autogenComment.c_str(), this->Dir.Work.c_str(), /*replace=*/false,
1252 /*escapeOldStyle=*/false,
1253 /*uses_terminal=*/false,
1254 /*command_expand_lists=*/false, this->AutogenTarget.DepFile);
1256 // Alter variables for the autogen target which now merely wraps the
1258 dependencies.clear();
1259 dependencies.push_back(outputFile);
1260 commandLines.clear();
1261 autogenComment.clear();
1264 // Create autogen target
1265 cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
1266 this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
1267 /*byproducts=*/autogenProvides,
1268 /*depends=*/dependencies, commandLines, false, autogenComment.c_str());
1269 // Create autogen generator target
1270 this->LocalGen->AddGeneratorTarget(
1271 cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
1273 // Forward origin utilities to autogen target
1274 if (this->AutogenTarget.DependOrigin) {
1275 for (BT<std::pair<std::string, bool>> const& depName :
1276 this->GenTarget->GetUtilities()) {
1277 autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
1280 if (!useNinjaDepfile) {
1281 // Add additional autogen target dependencies to autogen target
1282 for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1283 autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
1287 // Set FOLDER property in autogen target
1288 if (!this->TargetsFolder.empty()) {
1289 autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
1292 // Add autogen target to the origin target dependencies
1293 this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
1296 // Add autogen target to the global autogen target dependencies
1297 if (this->AutogenTarget.GlobalTarget) {
1298 this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
1299 this->AutogenTarget.Name);
1306 bool cmQtAutoGenInitializer::InitRccTargets()
1308 for (Qrc const& qrc : this->Rcc.Qrcs) {
1309 // Register info file as generated by CMake
1310 this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
1311 // Register file at target
1313 cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
1314 sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
1317 std::vector<std::string> ccOutput;
1318 ccOutput.push_back(qrc.OutputFile);
1320 std::vector<std::string> ccDepends;
1321 // Add the .qrc and info file to the custom command dependencies
1322 ccDepends.push_back(qrc.QrcFile);
1323 ccDepends.push_back(qrc.InfoFile);
1325 cmCustomCommandLines commandLines;
1326 if (this->MultiConfig) {
1327 // Build for all configurations
1328 for (std::string const& config : this->ConfigsList) {
1329 commandLines.push_back(
1330 cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1331 "cmake_autorcc", qrc.InfoFile, config }));
1334 commandLines.push_back(
1335 cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1336 "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
1338 std::string ccComment =
1339 cmStrCat("Automatic RCC for ",
1340 FileProjectRelativePath(this->Makefile, qrc.QrcFile));
1342 if (qrc.Generated || this->Rcc.GlobalTarget) {
1343 // Create custom rcc target
1346 ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
1348 ccName += cmStrCat('_', qrc.QrcPathChecksum);
1351 cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
1352 ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
1353 commandLines, false, ccComment.c_str());
1355 // Create autogen generator target
1356 this->LocalGen->AddGeneratorTarget(
1357 cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
1359 // Set FOLDER property in autogen target
1360 if (!this->TargetsFolder.empty()) {
1361 autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
1363 if (!this->Rcc.ExecutableTargetName.empty()) {
1364 autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
1368 // Add autogen target to the origin target dependencies
1369 this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
1371 // Add autogen target to the global autogen target dependencies
1372 if (this->Rcc.GlobalTarget) {
1373 this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
1376 // Create custom rcc command
1378 std::vector<std::string> ccByproducts;
1380 // Add the resource files to the dependencies
1381 for (std::string const& fileName : qrc.Resources) {
1382 // Add resource file to the custom command dependencies
1383 ccDepends.push_back(fileName);
1385 if (!this->Rcc.ExecutableTargetName.empty()) {
1386 ccDepends.push_back(this->Rcc.ExecutableTargetName);
1388 std::string no_main_dependency;
1389 cmImplicitDependsList no_implicit_depends;
1390 this->LocalGen->AddCustomCommandToOutput(
1391 ccOutput, ccByproducts, ccDepends, no_main_dependency,
1392 no_implicit_depends, commandLines, ccComment.c_str(),
1393 this->Dir.Work.c_str());
1395 // Reconfigure when .qrc file changes
1396 this->Makefile->AddCMakeDependFile(qrc.QrcFile);
1403 bool cmQtAutoGenInitializer::SetupCustomTargets()
1405 // Create info directory on demand
1406 if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
1407 cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
1408 Quoted(this->Dir.Info)));
1412 // Generate autogen target info file
1413 if (this->MocOrUicEnabled()) {
1414 // Write autogen target info files
1415 if (!this->SetupWriteAutogenInfo()) {
1420 // Write AUTORCC info files
1421 return !this->Rcc.Enabled || this->SetupWriteRccInfo();
1424 bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
1427 auto MfDef = [this](std::string const& key) {
1428 return this->Makefile->GetSafeDefinition(key);
1431 // Filtered headers and sources
1432 std::set<std::string> moc_skip;
1433 std::set<std::string> uic_skip;
1434 std::vector<MUFile const*> headers;
1435 std::vector<MUFile const*> sources;
1439 headers.reserve(this->AutogenTarget.Headers.size());
1440 for (auto const& pair : this->AutogenTarget.Headers) {
1441 MUFile const* const muf = pair.second.get();
1442 if (muf->Generated && !this->CMP0071Accept) {
1446 moc_skip.insert(muf->FullPath);
1449 uic_skip.insert(muf->FullPath);
1451 if (muf->MocIt || muf->UicIt) {
1452 headers.emplace_back(muf);
1455 std::sort(headers.begin(), headers.end(),
1456 [](MUFile const* a, MUFile const* b) {
1457 return (a->FullPath < b->FullPath);
1463 sources.reserve(this->AutogenTarget.Sources.size());
1464 for (auto const& pair : this->AutogenTarget.Sources) {
1465 MUFile const* const muf = pair.second.get();
1466 if (muf->Generated && !this->CMP0071Accept) {
1470 moc_skip.insert(muf->FullPath);
1473 uic_skip.insert(muf->FullPath);
1475 if (muf->MocIt || muf->UicIt) {
1476 sources.emplace_back(muf);
1479 std::sort(sources.begin(), sources.end(),
1480 [](MUFile const* a, MUFile const* b) {
1481 return (a->FullPath < b->FullPath);
1489 info.SetBool("MULTI_CONFIG", this->MultiConfig);
1490 info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
1491 info.SetUInt("VERBOSITY", this->Verbosity);
1494 info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1495 info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1496 info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1497 info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1498 info.Set("BUILD_DIR", this->Dir.Build);
1499 info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1501 info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
1502 info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
1503 info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
1504 info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
1506 info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
1507 info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
1508 info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
1509 info.Set("DEP_FILE", this->AutogenTarget.DepFile);
1510 info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
1511 info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
1512 info.SetArray("HEADER_EXTENSIONS",
1513 this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
1515 "HEADERS", headers, [this](Json::Value& jval, MUFile const* muf) {
1517 jval[0u] = muf->FullPath;
1518 jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1519 jval[2u] = this->GetMocBuildPath(*muf);
1522 "SOURCES", sources, [](Json::Value& jval, MUFile const* muf) {
1524 jval[0u] = muf->FullPath;
1525 jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1528 // Write moc settings
1529 if (this->Moc.Enabled) {
1530 info.SetArray("MOC_SKIP", moc_skip);
1531 info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
1532 info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
1533 info.SetArray("MOC_OPTIONS", this->Moc.Options);
1534 info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
1535 info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
1536 info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
1538 "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
1539 [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
1541 jval[0u] = pair.first;
1542 jval[1u] = pair.second;
1544 info.Set("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
1545 info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
1546 info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
1549 // Write uic settings
1550 if (this->Uic.Enabled) {
1551 // Add skipped .ui files
1552 uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
1554 info.SetArray("UIC_SKIP", uic_skip);
1555 info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFiles,
1556 [](Json::Value& jval, UicT::UiFileT const& uiFile) {
1558 jval[0u] = uiFile.first;
1559 InfoWriter::MakeStringArray(jval[1u], uiFile.second);
1561 info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
1562 info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
1565 info.Save(this->AutogenTarget.InfoFile);
1570 bool cmQtAutoGenInitializer::SetupWriteRccInfo()
1572 for (Qrc const& qrc : this->Rcc.Qrcs) {
1574 auto MfDef = [this](std::string const& key) {
1575 return this->Makefile->GetSafeDefinition(key);
1581 info.SetBool("MULTI_CONFIG", this->MultiConfig);
1582 info.SetUInt("VERBOSITY", this->Verbosity);
1585 info.Set("LOCK_FILE", qrc.LockFile);
1586 info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
1589 info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1590 info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1591 info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1592 info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1593 info.Set("BUILD_DIR", this->Dir.Build);
1594 info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1597 info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
1598 info.SetArray("RCC_LIST_OPTIONS",
1599 this->Rcc.ExecutableFeatures->ListOptions);
1602 info.Set("SOURCE", qrc.QrcFile);
1603 info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
1604 info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
1605 info.SetArray("OPTIONS", qrc.Options);
1606 info.SetArray("INPUTS", qrc.Resources);
1608 info.Save(qrc.InfoFile);
1614 cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
1615 std::string const& filename)
1617 cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
1618 gFile->SetProperty("GENERATED", "1");
1619 gFile->SetProperty("SKIP_AUTOGEN", "1");
1623 cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
1624 std::string const& filename, GenVarsT const& genVars, bool prepend)
1626 // Register source at makefile
1627 cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
1628 // Add source file to target
1629 this->GenTarget->AddSource(filename, prepend);
1631 // Add source file to source group
1632 this->AddToSourceGroup(filename, genVars.GenNameUpper);
1637 void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
1638 cm::string_view genNameUpper)
1640 cmSourceGroup* sourceGroup = nullptr;
1641 // Acquire source group
1643 std::string property;
1644 std::string groupName;
1646 // Prefer generator specific source group name
1647 std::initializer_list<std::string> const props{
1648 cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
1650 for (std::string const& prop : props) {
1651 const char* propName =
1652 this->Makefile->GetState()->GetGlobalProperty(prop);
1653 if ((propName != nullptr) && (*propName != '\0')) {
1654 groupName = propName;
1660 // Generate a source group on demand
1661 if (!groupName.empty()) {
1662 sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
1663 if (sourceGroup == nullptr) {
1664 cmSystemTools::Error(
1665 cmStrCat(genNameUpper, " error in ", property,
1666 ": Could not find or create the source group ",
1667 cmQtAutoGen::Quoted(groupName)));
1671 if (sourceGroup != nullptr) {
1672 sourceGroup->AddGroupFile(fileName);
1676 void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
1678 this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
1682 void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
1683 cm::string_view prefix,
1684 cm::string_view suffix)
1686 configString.Default = cmStrCat(prefix, suffix);
1687 if (this->MultiConfig) {
1688 for (auto const& cfg : this->ConfigsList) {
1689 configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
1694 void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
1696 this->AddCleanFile(configString.Default);
1697 if (this->MultiConfig) {
1698 for (auto const& pair : configString.Config) {
1699 this->AddCleanFile(pair.second);
1704 std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
1705 cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
1707 // Converts a char ptr to an unsigned int value
1708 auto toUInt = [](const char* const input) -> unsigned int {
1709 unsigned long tmp = 0;
1710 if (input != nullptr && cmStrToULong(input, &tmp)) {
1711 return static_cast<unsigned int>(tmp);
1716 // Initialize return value to a default
1717 std::pair<IntegerVersion, unsigned int> res(
1719 toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
1722 // Acquire known Qt versions
1723 std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
1725 // Qt version variable prefixes
1726 static std::initializer_list<
1727 std::pair<cm::string_view, cm::string_view>> const keys{
1728 { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
1729 { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
1730 { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
1733 knownQtVersions.reserve(keys.size() * 2);
1735 // Adds a version to the result (nullptr safe)
1736 auto addVersion = [&knownQtVersions, &toUInt](const char* major,
1737 const char* minor) {
1738 cmQtAutoGen::IntegerVersion ver(toUInt(major), toUInt(minor));
1739 if (ver.Major != 0) {
1740 knownQtVersions.emplace_back(ver);
1744 // Read versions from variables
1745 for (auto const& keyPair : keys) {
1746 addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
1747 target->Makefile->GetDefinition(std::string(keyPair.second)));
1750 // Read versions from directory properties
1751 for (auto const& keyPair : keys) {
1752 addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
1753 target->Makefile->GetProperty(std::string(keyPair.second)));
1757 // Evaluate known Qt versions
1758 if (!knownQtVersions.empty()) {
1759 if (res.second == 0) {
1760 // No specific version was requested by the target:
1761 // Use highest known Qt version.
1762 res.first = knownQtVersions.at(0);
1764 // Pick a version from the known versions:
1765 for (auto it : knownQtVersions) {
1766 if (it.Major == res.second) {
1776 std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
1783 std::string basePath =
1784 cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
1785 FileNameWithoutLastExtension(muf.FullPath));
1787 res = cmStrCat(basePath, ".cpp");
1788 if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1792 // File name already emitted.
1793 // Try appending the header suffix to the base path.
1794 basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
1795 res = cmStrCat(basePath, ".cpp");
1796 if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1800 // File name with header extension already emitted.
1801 // Try adding a number to the base path.
1802 constexpr std::size_t number_begin = 2;
1803 constexpr std::size_t number_end = 256;
1804 for (std::size_t ii = number_begin; ii != number_end; ++ii) {
1805 res = cmStrCat(basePath, '_', ii, ".cpp");
1806 if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1811 // Output file name conflict (unlikely, but still...)
1812 cmSystemTools::Error(
1813 cmStrCat("moc output file name conflict for ", muf.FullPath));
1818 bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
1819 const std::string& executable,
1820 bool ignoreMissingTarget) const
1822 auto print_err = [this, &genVars](std::string const& err) {
1823 cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
1824 this->GenTarget->GetName(), ": ", err));
1827 // Custom executable
1829 std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
1830 std::string const val = this->GenTarget->Target->GetSafeProperty(prop);
1832 // Evaluate generator expression
1834 cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
1835 cmGeneratorExpression ge(lfbt);
1836 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
1837 genVars.Executable = cge->Evaluate(this->LocalGen, "");
1839 if (genVars.Executable.empty() && !ignoreMissingTarget) {
1840 print_err(prop + " evaluates to an empty value");
1844 // Create empty compiler features.
1845 genVars.ExecutableFeatures =
1846 std::make_shared<cmQtAutoGen::CompilerFeatures>();
1851 // Find executable target
1853 // Find executable target name
1854 cm::string_view prefix;
1855 if (this->QtVersion.Major == 4) {
1857 } else if (this->QtVersion.Major == 5) {
1859 } else if (this->QtVersion.Major == 6) {
1862 std::string const targetName = cmStrCat(prefix, executable);
1865 cmGeneratorTarget* genTarget =
1866 this->LocalGen->FindGeneratorTargetToUse(targetName);
1867 if (genTarget != nullptr) {
1868 genVars.ExecutableTargetName = targetName;
1869 genVars.ExecutableTarget = genTarget;
1870 if (genTarget->IsImported()) {
1871 genVars.Executable = genTarget->ImportedGetLocation("");
1873 genVars.Executable = genTarget->GetLocation("");
1876 if (ignoreMissingTarget) {
1877 // Create empty compiler features.
1878 genVars.ExecutableFeatures =
1879 std::make_shared<cmQtAutoGen::CompilerFeatures>();
1882 print_err(cmStrCat("Could not find ", executable, " executable target ",
1888 // Get executable features
1891 genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
1892 executable, genVars.Executable, err);
1893 if (!genVars.ExecutableFeatures) {