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 "cmExportFileGenerator.h"
13 #include "cmsys/FStream.hxx"
15 #include "cmComputeLinkInformation.h"
16 #include "cmFileSet.h"
17 #include "cmGeneratedFileStream.h"
18 #include "cmGeneratorTarget.h"
19 #include "cmLinkItem.h"
20 #include "cmLocalGenerator.h"
21 #include "cmMakefile.h"
22 #include "cmMessageType.h"
23 #include "cmOutputConverter.h"
24 #include "cmPolicies.h"
25 #include "cmPropertyMap.h"
26 #include "cmStateTypes.h"
27 #include "cmStringAlgorithms.h"
28 #include "cmSystemTools.h"
32 static std::string cmExportFileGeneratorEscape(std::string const& str)
34 // Escape a property value for writing into a .cmake file.
35 std::string result = cmOutputConverter::EscapeForCMake(str);
36 // Un-escape variable references generated by our own export code.
37 cmSystemTools::ReplaceString(result, "\\${_IMPORT_PREFIX}",
39 cmSystemTools::ReplaceString(result, "\\${CMAKE_IMPORT_LIBRARY_SUFFIX}",
40 "${CMAKE_IMPORT_LIBRARY_SUFFIX}");
44 cmExportFileGenerator::cmExportFileGenerator()
46 this->AppendMode = false;
47 this->ExportOld = false;
50 void cmExportFileGenerator::AddConfiguration(const std::string& config)
52 this->Configurations.push_back(config);
55 void cmExportFileGenerator::SetExportFile(const char* mainFile)
57 this->MainImportFile = mainFile;
58 this->FileDir = cmSystemTools::GetFilenamePath(this->MainImportFile);
60 cmSystemTools::GetFilenameWithoutLastExtension(this->MainImportFile);
62 cmSystemTools::GetFilenameLastExtension(this->MainImportFile);
65 const std::string& cmExportFileGenerator::GetMainExportFileName() const
67 return this->MainImportFile;
70 bool cmExportFileGenerator::GenerateImportFile()
72 // Open the output file to generate it.
73 std::unique_ptr<cmsys::ofstream> foutPtr;
74 if (this->AppendMode) {
76 auto openmodeApp = std::ios::app;
77 foutPtr = cm::make_unique<cmsys::ofstream>(this->MainImportFile.c_str(),
80 // Generate atomically and with copy-if-different.
81 std::unique_ptr<cmGeneratedFileStream> ap(
82 new cmGeneratedFileStream(this->MainImportFile, true));
83 ap->SetCopyIfDifferent(true);
84 foutPtr = std::move(ap);
86 if (!foutPtr || !*foutPtr) {
87 std::string se = cmSystemTools::GetLastSystemError();
89 e << "cannot write to file \"" << this->MainImportFile << "\": " << se;
90 cmSystemTools::Error(e.str());
93 std::ostream& os = *foutPtr;
95 // Start with the import file header.
96 this->GeneratePolicyHeaderCode(os);
97 this->GenerateImportHeaderCode(os);
99 // Create all the imported targets.
100 bool result = this->GenerateMainFile(os);
102 // End with the import file footer.
103 this->GenerateImportFooterCode(os);
104 this->GeneratePolicyFooterCode(os);
109 void cmExportFileGenerator::GenerateImportConfig(std::ostream& os,
110 const std::string& config)
112 // Construct the property configuration suffix.
113 std::string suffix = "_";
114 if (!config.empty()) {
115 suffix += cmSystemTools::UpperCase(config);
117 suffix += "NOCONFIG";
120 // Generate the per-config target information.
121 this->GenerateImportTargetsConfig(os, config, suffix);
124 void cmExportFileGenerator::PopulateInterfaceProperty(
125 const std::string& propName, cmGeneratorTarget const* target,
126 ImportPropertyMap& properties)
128 cmValue input = target->GetProperty(propName);
130 properties[propName] = *input;
134 void cmExportFileGenerator::PopulateInterfaceProperty(
135 const std::string& propName, const std::string& outputName,
136 cmGeneratorTarget const* target,
137 cmGeneratorExpression::PreprocessContext preprocessRule,
138 ImportPropertyMap& properties)
140 cmValue input = target->GetProperty(propName);
142 if (input->empty()) {
144 properties[outputName].clear();
149 cmGeneratorExpression::Preprocess(*input, preprocessRule);
150 if (!prepro.empty()) {
151 this->ResolveTargetsInGeneratorExpressions(prepro, target);
152 properties[outputName] = prepro;
157 void cmExportFileGenerator::GenerateRequiredCMakeVersion(
158 std::ostream& os, const char* versionString)
160 /* clang-format off */
161 os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n"
162 " message(FATAL_ERROR \"This file relies on consumers using "
163 "CMake " << versionString << " or greater.\")\n"
165 /* clang-format on */
168 bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty(
169 cmGeneratorTarget const* target,
170 cmGeneratorExpression::PreprocessContext preprocessRule,
171 ImportPropertyMap& properties)
173 if (!target->IsLinkable()) {
176 static const std::array<std::string, 3> linkIfaceProps = {
177 { "INTERFACE_LINK_LIBRARIES", "INTERFACE_LINK_LIBRARIES_DIRECT",
178 "INTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE" }
180 bool hadINTERFACE_LINK_LIBRARIES = false;
181 for (std::string const& linkIfaceProp : linkIfaceProps) {
182 if (cmValue input = target->GetProperty(linkIfaceProp)) {
184 cmGeneratorExpression::Preprocess(*input, preprocessRule);
185 if (!prepro.empty()) {
186 this->ResolveTargetsInGeneratorExpressions(prepro, target,
188 properties[linkIfaceProp] = prepro;
189 hadINTERFACE_LINK_LIBRARIES = true;
193 return hadINTERFACE_LINK_LIBRARIES;
196 static bool isSubDirectory(std::string const& a, std::string const& b)
198 return (cmSystemTools::ComparePath(a, b) ||
199 cmSystemTools::IsSubDirectory(a, b));
202 static bool checkInterfaceDirs(const std::string& prepro,
203 cmGeneratorTarget const* target,
204 const std::string& prop)
206 std::string const& installDir =
207 target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
208 std::string const& topSourceDir =
209 target->GetLocalGenerator()->GetSourceDirectory();
210 std::string const& topBinaryDir =
211 target->GetLocalGenerator()->GetBinaryDirectory();
213 std::vector<std::string> parts;
214 cmGeneratorExpression::Split(prepro, parts);
216 const bool inSourceBuild = topSourceDir == topBinaryDir;
218 bool hadFatalError = false;
220 for (std::string const& li : parts) {
221 size_t genexPos = cmGeneratorExpression::Find(li);
225 if (cmHasLiteralPrefix(li, "${_IMPORT_PREFIX}")) {
228 MessageType messageType = MessageType::FATAL_ERROR;
229 std::ostringstream e;
230 if (genexPos != std::string::npos) {
231 if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
232 switch (target->GetPolicyStatusCMP0041()) {
233 case cmPolicies::WARN:
234 messageType = MessageType::WARNING;
235 e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0041) << "\n";
237 case cmPolicies::OLD:
239 case cmPolicies::REQUIRED_IF_USED:
240 case cmPolicies::REQUIRED_ALWAYS:
241 case cmPolicies::NEW:
242 hadFatalError = true;
243 break; // Issue fatal message.
246 hadFatalError = true;
249 if (!cmSystemTools::FileIsFullPath(li)) {
250 /* clang-format off */
251 e << "Target \"" << target->GetName() << "\" " << prop <<
252 " property contains relative path:\n"
254 /* clang-format on */
255 target->GetLocalGenerator()->IssueMessage(messageType, e.str());
257 bool inBinary = isSubDirectory(li, topBinaryDir);
258 bool inSource = isSubDirectory(li, topSourceDir);
259 if (isSubDirectory(li, installDir)) {
260 // The include directory is inside the install tree. If the
261 // install tree is not inside the source tree or build tree then
262 // fall through to the checks below that the include directory is not
263 // also inside the source tree or build tree.
264 bool shouldContinue =
265 (!inBinary || isSubDirectory(installDir, topBinaryDir)) &&
266 (!inSource || isSubDirectory(installDir, topSourceDir));
268 if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
269 if (!shouldContinue) {
270 switch (target->GetPolicyStatusCMP0052()) {
271 case cmPolicies::WARN: {
272 std::ostringstream s;
273 s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n";
274 s << "Directory:\n \"" << li
276 "INTERFACE_INCLUDE_DIRECTORIES of target \""
278 << "\" is a subdirectory of the install "
281 << "\"\nhowever it is also "
282 "a subdirectory of the "
283 << (inBinary ? "build" : "source") << " tree:\n \""
284 << (inBinary ? topBinaryDir : topSourceDir) << "\"\n";
285 target->GetLocalGenerator()->IssueMessage(
286 MessageType::AUTHOR_WARNING, s.str());
289 case cmPolicies::OLD:
290 shouldContinue = true;
292 case cmPolicies::REQUIRED_ALWAYS:
293 case cmPolicies::REQUIRED_IF_USED:
294 case cmPolicies::NEW:
299 if (shouldContinue) {
304 /* clang-format off */
305 e << "Target \"" << target->GetName() << "\" " << prop <<
306 " property contains path:\n"
307 " \"" << li << "\"\nwhich is prefixed in the build directory.";
308 /* clang-format on */
309 target->GetLocalGenerator()->IssueMessage(messageType, e.str());
311 if (!inSourceBuild) {
313 e << "Target \"" << target->GetName() << "\" " << prop
314 << " property contains path:\n"
316 << li << "\"\nwhich is prefixed in the source directory.";
317 target->GetLocalGenerator()->IssueMessage(messageType, e.str());
321 return !hadFatalError;
324 static void prefixItems(std::string& exportDirs)
326 std::vector<std::string> entries;
327 cmGeneratorExpression::Split(exportDirs, entries);
329 const char* sep = "";
330 for (std::string const& e : entries) {
333 if (!cmSystemTools::FileIsFullPath(e) &&
334 e.find("${_IMPORT_PREFIX}") == std::string::npos) {
335 exportDirs += "${_IMPORT_PREFIX}/";
341 void cmExportFileGenerator::PopulateSourcesInterface(
342 cmGeneratorTarget const* gt,
343 cmGeneratorExpression::PreprocessContext preprocessRule,
344 ImportPropertyMap& properties)
346 assert(preprocessRule == cmGeneratorExpression::InstallInterface);
348 const char* propName = "INTERFACE_SOURCES";
349 cmValue input = gt->GetProperty(propName);
355 if (input->empty()) {
356 properties[propName].clear();
361 cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
362 if (!prepro.empty()) {
363 this->ResolveTargetsInGeneratorExpressions(prepro, gt);
365 if (!checkInterfaceDirs(prepro, gt, propName)) {
368 properties[propName] = prepro;
372 void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
373 cmGeneratorTarget const* target,
374 cmGeneratorExpression::PreprocessContext preprocessRule,
375 ImportPropertyMap& properties, cmTargetExport const& te)
377 assert(preprocessRule == cmGeneratorExpression::InstallInterface);
379 const char* propName = "INTERFACE_INCLUDE_DIRECTORIES";
380 cmValue input = target->GetProperty(propName);
382 cmGeneratorExpression ge;
384 std::string dirs = cmGeneratorExpression::Preprocess(
385 cmJoin(target->Target->GetInstallIncludeDirectoriesEntries(te), ";"),
386 preprocessRule, true);
387 this->ReplaceInstallPrefix(dirs);
388 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
389 std::string exportDirs =
390 cge->Evaluate(target->GetLocalGenerator(), "", target);
392 if (cge->GetHadContextSensitiveCondition()) {
393 cmLocalGenerator* lg = target->GetLocalGenerator();
394 std::ostringstream e;
395 e << "Target \"" << target->GetName()
396 << "\" is installed with "
397 "INCLUDES DESTINATION set to a context sensitive path. Paths which "
398 "depend on the configuration, policy values or the link interface "
400 "not supported. Consider using target_include_directories instead.";
401 lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
405 if (!input && exportDirs.empty()) {
408 if ((input && input->empty()) && exportDirs.empty()) {
410 properties[propName].clear();
414 prefixItems(exportDirs);
416 std::string includes = (input ? *input : "");
417 const char* sep = input ? ";" : "";
418 includes += sep + exportDirs;
420 cmGeneratorExpression::Preprocess(includes, preprocessRule, true);
421 if (!prepro.empty()) {
422 this->ResolveTargetsInGeneratorExpressions(prepro, target);
424 if (!checkInterfaceDirs(prepro, target, propName)) {
427 properties[propName] = prepro;
431 void cmExportFileGenerator::PopulateLinkDependsInterface(
432 cmGeneratorTarget const* gt,
433 cmGeneratorExpression::PreprocessContext preprocessRule,
434 ImportPropertyMap& properties)
436 assert(preprocessRule == cmGeneratorExpression::InstallInterface);
438 const char* propName = "INTERFACE_LINK_DEPENDS";
439 cmValue input = gt->GetProperty(propName);
445 if (input->empty()) {
446 properties[propName].clear();
451 cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
452 if (!prepro.empty()) {
453 this->ResolveTargetsInGeneratorExpressions(prepro, gt);
455 if (!checkInterfaceDirs(prepro, gt, propName)) {
458 properties[propName] = prepro;
462 void cmExportFileGenerator::PopulateLinkDirectoriesInterface(
463 cmGeneratorTarget const* gt,
464 cmGeneratorExpression::PreprocessContext preprocessRule,
465 ImportPropertyMap& properties)
467 assert(preprocessRule == cmGeneratorExpression::InstallInterface);
469 const char* propName = "INTERFACE_LINK_DIRECTORIES";
470 cmValue input = gt->GetProperty(propName);
476 if (input->empty()) {
477 properties[propName].clear();
482 cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
483 if (!prepro.empty()) {
484 this->ResolveTargetsInGeneratorExpressions(prepro, gt);
486 if (!checkInterfaceDirs(prepro, gt, propName)) {
489 properties[propName] = prepro;
493 void cmExportFileGenerator::PopulateInterfaceProperty(
494 const std::string& propName, cmGeneratorTarget const* target,
495 cmGeneratorExpression::PreprocessContext preprocessRule,
496 ImportPropertyMap& properties)
498 this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
502 static void getPropertyContents(cmGeneratorTarget const* tgt,
503 const std::string& prop,
504 std::set<std::string>& ifaceProperties)
506 cmValue p = tgt->GetProperty(prop);
510 std::vector<std::string> content = cmExpandedList(*p);
511 ifaceProperties.insert(content.begin(), content.end());
514 static void getCompatibleInterfaceProperties(
515 cmGeneratorTarget const* target, std::set<std::string>& ifaceProperties,
516 const std::string& config)
518 if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
519 // object libraries have no link information, so nothing to compute
523 cmComputeLinkInformation* info = target->GetLinkInformation(config);
526 cmLocalGenerator* lg = target->GetLocalGenerator();
527 std::ostringstream e;
528 e << "Exporting the target \"" << target->GetName()
530 "allowed since its linker language cannot be determined";
531 lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
535 const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
537 for (auto const& dep : deps) {
541 getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL",
543 getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING",
545 getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
547 getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
552 void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
553 cmGeneratorTarget const* gtarget, ImportPropertyMap& properties)
555 this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
557 this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
559 this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
561 this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
564 std::set<std::string> ifaceProperties;
566 getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
567 getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
568 getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
570 getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
573 if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
574 std::vector<std::string> configNames =
575 gtarget->Target->GetMakefile()->GetGeneratorConfigs(
576 cmMakefile::IncludeEmptyConfig);
578 for (std::string const& cn : configNames) {
579 getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn);
583 for (std::string const& ip : ifaceProperties) {
584 this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties);
588 void cmExportFileGenerator::GenerateInterfaceProperties(
589 const cmGeneratorTarget* target, std::ostream& os,
590 const ImportPropertyMap& properties)
592 if (!properties.empty()) {
593 std::string targetName =
594 cmStrCat(this->Namespace, target->GetExportName());
595 os << "set_target_properties(" << targetName << " PROPERTIES\n";
596 for (auto const& property : properties) {
597 os << " " << property.first << " "
598 << cmExportFileGeneratorEscape(property.second) << "\n";
604 bool cmExportFileGenerator::AddTargetNamespace(std::string& input,
605 cmGeneratorTarget const* target,
606 cmLocalGenerator const* lg)
608 cmGeneratorTarget::TargetOrString resolved =
609 target->ResolveTargetReference(input, lg);
611 cmGeneratorTarget* tgt = resolved.Target;
613 input = resolved.String;
617 if (tgt->IsImported()) {
618 input = tgt->GetName();
621 if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
622 input = this->Namespace + tgt->GetExportName();
624 std::string namespacedTarget;
625 this->HandleMissingTarget(namespacedTarget, target, tgt);
626 if (!namespacedTarget.empty()) {
627 input = namespacedTarget;
629 input = tgt->GetName();
635 void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
636 std::string& input, cmGeneratorTarget const* target,
637 FreeTargetsReplace replace)
639 cmLocalGenerator const* lg = target->GetLocalGenerator();
640 if (replace == NoReplaceFreeTargets) {
641 this->ResolveTargetsInGeneratorExpression(input, target, lg);
644 std::vector<std::string> parts;
645 cmGeneratorExpression::Split(input, parts);
649 for (std::string& li : parts) {
650 if (target->IsLinkLookupScope(li, lg)) {
653 if (cmGeneratorExpression::Find(li) == std::string::npos) {
654 this->AddTargetNamespace(li, target, lg);
656 this->ResolveTargetsInGeneratorExpression(li, target, lg);
663 void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
664 std::string& input, cmGeneratorTarget const* target,
665 cmLocalGenerator const* lg)
667 std::string::size_type pos = 0;
668 std::string::size_type lastPos = pos;
670 while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) !=
672 std::string::size_type nameStartPos =
673 pos + sizeof("$<TARGET_PROPERTY:") - 1;
674 std::string::size_type closePos = input.find('>', nameStartPos);
675 std::string::size_type commaPos = input.find(',', nameStartPos);
676 std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
677 if (commaPos == std::string::npos // Implied 'this' target
678 || closePos == std::string::npos // Incomplete expression.
679 || closePos < commaPos // Implied 'this' target
680 || nextOpenPos < commaPos) // Non-literal
682 lastPos = nameStartPos;
686 std::string targetName =
687 input.substr(nameStartPos, commaPos - nameStartPos);
689 if (this->AddTargetNamespace(targetName, target, lg)) {
690 input.replace(nameStartPos, commaPos - nameStartPos, targetName);
692 lastPos = nameStartPos + targetName.size() + 1;
695 std::string errorString;
698 while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) {
699 std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1;
700 std::string::size_type endPos = input.find('>', nameStartPos);
701 if (endPos == std::string::npos) {
702 errorString = "$<TARGET_NAME:...> expression incomplete";
705 std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
706 if (targetName.find("$<") != std::string::npos) {
707 errorString = "$<TARGET_NAME:...> requires its parameter to be a "
711 if (!this->AddTargetNamespace(targetName, target, lg)) {
712 errorString = "$<TARGET_NAME:...> requires its parameter to be a "
716 input.replace(pos, endPos - pos + 1, targetName);
717 lastPos = pos + targetName.size();
722 while (errorString.empty() &&
723 (pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) {
724 std::string::size_type nameStartPos = pos + sizeof("$<LINK_ONLY:") - 1;
725 std::string::size_type endPos = input.find('>', nameStartPos);
726 if (endPos == std::string::npos) {
727 errorString = "$<LINK_ONLY:...> expression incomplete";
730 std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
731 if (cmGeneratorExpression::IsValidTargetName(libName) &&
732 this->AddTargetNamespace(libName, target, lg)) {
733 input.replace(nameStartPos, endPos - nameStartPos, libName);
735 lastPos = nameStartPos + libName.size() + 1;
738 this->ReplaceInstallPrefix(input);
740 if (!errorString.empty()) {
741 target->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
746 void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
751 void cmExportFileGenerator::SetImportLinkInterface(
752 const std::string& config, std::string const& suffix,
753 cmGeneratorExpression::PreprocessContext preprocessRule,
754 cmGeneratorTarget const* target, ImportPropertyMap& properties)
756 // Add the transitive link dependencies for this configuration.
757 cmLinkInterface const* iface = target->GetLinkInterface(config, target);
762 if (iface->ImplementationIsInterface) {
763 // Policy CMP0022 must not be NEW.
764 this->SetImportLinkProperty(
765 suffix, target, "IMPORTED_LINK_INTERFACE_LIBRARIES", iface->Libraries,
766 properties, ImportLinkPropertyTargetNames::Yes);
772 if (cmValue prop_suffixed =
773 target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
774 propContent = prop_suffixed;
775 } else if (cmValue prop = target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
781 const bool newCMP0022Behavior =
782 target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
783 target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
785 if (newCMP0022Behavior && !this->ExportOld) {
786 cmLocalGenerator* lg = target->GetLocalGenerator();
787 std::ostringstream e;
788 e << "Target \"" << target->GetName()
789 << "\" has policy CMP0022 enabled, "
790 "but also has old-style LINK_INTERFACE_LIBRARIES properties "
791 "populated, but it was exported without the "
792 "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
793 lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
797 if (propContent->empty()) {
798 properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear();
803 cmGeneratorExpression::Preprocess(*propContent, preprocessRule);
804 if (!prepro.empty()) {
805 this->ResolveTargetsInGeneratorExpressions(prepro, target,
807 properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
811 void cmExportFileGenerator::SetImportDetailProperties(
812 const std::string& config, std::string const& suffix,
813 cmGeneratorTarget* target, ImportPropertyMap& properties)
815 // Get the makefile in which to lookup target information.
816 cmMakefile* mf = target->Makefile;
818 // Add the soname for unix shared libraries.
819 if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
820 target->GetType() == cmStateEnums::MODULE_LIBRARY) {
821 if (!target->IsDLLPlatform()) {
824 if (target->HasSOName(config)) {
825 if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
826 value = this->InstallNameDir(target, config);
828 prop = "IMPORTED_SONAME";
829 value += target->GetSOName(config);
831 prop = "IMPORTED_NO_SONAME";
835 properties[prop] = value;
839 // Add the transitive link dependencies for this configuration.
840 if (cmLinkInterface const* iface =
841 target->GetLinkInterface(config, target)) {
842 this->SetImportLinkProperty(
843 suffix, target, "IMPORTED_LINK_INTERFACE_LANGUAGES", iface->Languages,
844 properties, ImportLinkPropertyTargetNames::No);
846 this->SetImportLinkProperty(
847 suffix, target, "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps,
848 properties, ImportLinkPropertyTargetNames::Yes);
849 if (iface->Multiplicity > 0) {
851 cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
852 properties[prop] = std::to_string(iface->Multiplicity);
856 // Add information if this target is a managed target
857 if (target->GetManagedType(config) !=
858 cmGeneratorTarget::ManagedType::Native) {
859 std::string prop = cmStrCat("IMPORTED_COMMON_LANGUAGE_RUNTIME", suffix);
861 if (cmValue p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
863 } else if (target->IsCSharpOnly()) {
864 // C# projects do not have the /clr flag, so we set the property
865 // here to mark the target as (only) managed (i.e. no .lib file
866 // to link to). Otherwise the COMMON_LANGUAGE_RUNTIME target
867 // property would have to be set manually for C# targets to make
868 // exporting/importing work.
871 properties[prop] = propval;
875 static std::string const& asString(std::string const& l)
880 static std::string const& asString(cmLinkItem const& l)
885 template <typename T>
886 void cmExportFileGenerator::SetImportLinkProperty(
887 std::string const& suffix, cmGeneratorTarget const* target,
888 const std::string& propName, std::vector<T> const& entries,
889 ImportPropertyMap& properties, ImportLinkPropertyTargetNames targetNames)
891 // Skip the property if there are no entries.
892 if (entries.empty()) {
896 cmLocalGenerator const* lg = target->GetLocalGenerator();
898 // Construct the property value.
899 std::string link_entries;
900 const char* sep = "";
901 for (T const& l : entries) {
902 // Separate this from the previous entry.
906 if (targetNames == ImportLinkPropertyTargetNames::Yes) {
907 std::string temp = asString(l);
908 this->AddTargetNamespace(temp, target, lg);
909 link_entries += temp;
911 link_entries += asString(l);
915 // Store the property.
916 std::string prop = cmStrCat(propName, suffix);
917 properties[prop] = link_entries;
920 void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
922 // Protect that file against use with older CMake versions.
923 /* clang-format off */
924 os << "# Generated by CMake\n\n";
925 os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.8)\n"
926 << " message(FATAL_ERROR \"CMake >= 2.8.0 required\")\n"
928 << "if(CMAKE_VERSION VERSION_LESS \"2.8.3\")\n"
929 << " message(FATAL_ERROR \"CMake >= 2.8.3 required\")\n"
931 /* clang-format on */
933 // Isolate the file policy level.
934 // Support CMake versions as far back as 2.6 but also support using NEW
935 // policy settings for up to CMake 3.22 (this upper limit may be reviewed
936 // and increased from time to time). This reduces the opportunity for CMake
937 // warnings when an older export file is later used with newer CMake
939 /* clang-format off */
940 os << "cmake_policy(PUSH)\n"
941 << "cmake_policy(VERSION 2.8.3...3.22)\n";
942 /* clang-format on */
945 void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
947 os << "cmake_policy(POP)\n";
950 void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
951 const std::string& config)
953 os << "#----------------------------------------------------------------\n"
954 << "# Generated CMake target import file";
955 if (!config.empty()) {
956 os << " for configuration \"" << config << "\".\n";
960 os << "#----------------------------------------------------------------\n"
962 this->GenerateImportVersionCode(os);
965 void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
967 os << "# Commands beyond this point should not need to know the version.\n"
968 << "set(CMAKE_IMPORT_FILE_VERSION)\n";
971 void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
973 // Store an import file format version. This will let us change the
974 // format later while still allowing old import files to work.
975 /* clang-format off */
976 os << "# Commands may need to know the format version.\n"
977 << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
979 /* clang-format on */
982 void cmExportFileGenerator::GenerateExpectedTargetsCode(
983 std::ostream& os, const std::string& expectedTargets)
985 /* clang-format off */
986 os << "# Protect against multiple inclusion, which would fail when already "
987 "imported targets are added once more.\n"
988 "set(_cmake_targets_defined \"\")\n"
989 "set(_cmake_targets_not_defined \"\")\n"
990 "set(_cmake_expected_targets \"\")\n"
991 "foreach(_cmake_expected_target IN ITEMS " << expectedTargets << ")\n"
992 " list(APPEND _cmake_expected_targets \"${_cmake_expected_target}\")\n"
993 " if(TARGET \"${_cmake_expected_target}\")\n"
994 " list(APPEND _cmake_targets_defined \"${_cmake_expected_target}\")\n"
996 " list(APPEND _cmake_targets_not_defined \"${_cmake_expected_target}\")\n"
999 "unset(_cmake_expected_target)\n"
1000 "if(_cmake_targets_defined STREQUAL _cmake_expected_targets)\n"
1001 " unset(_cmake_targets_defined)\n"
1002 " unset(_cmake_targets_not_defined)\n"
1003 " unset(_cmake_expected_targets)\n"
1004 " unset(CMAKE_IMPORT_FILE_VERSION)\n"
1005 " cmake_policy(POP)\n"
1008 "if(NOT _cmake_targets_defined STREQUAL \"\")\n"
1009 " string(REPLACE \";\" \", \" _cmake_targets_defined_text \"${_cmake_targets_defined}\")\n"
1010 " string(REPLACE \";\" \", \" _cmake_targets_not_defined_text \"${_cmake_targets_not_defined}\")\n"
1011 " message(FATAL_ERROR \"Some (but not all) targets in this export "
1012 "set were already defined.\\nTargets Defined: ${_cmake_targets_defined_text}\\n"
1013 "Targets not yet defined: ${_cmake_targets_not_defined_text}\\n\")\n"
1015 "unset(_cmake_targets_defined)\n"
1016 "unset(_cmake_targets_not_defined)\n"
1017 "unset(_cmake_expected_targets)\n"
1019 /* clang-format on */
1022 void cmExportFileGenerator::GenerateImportTargetCode(
1023 std::ostream& os, cmGeneratorTarget const* target,
1024 cmStateEnums::TargetType targetType)
1026 // Construct the imported target name.
1027 std::string targetName = this->Namespace;
1029 targetName += target->GetExportName();
1031 // Create the imported target.
1032 os << "# Create imported target " << targetName << "\n";
1033 switch (targetType) {
1034 case cmStateEnums::EXECUTABLE:
1035 os << "add_executable(" << targetName << " IMPORTED)\n";
1037 case cmStateEnums::STATIC_LIBRARY:
1038 os << "add_library(" << targetName << " STATIC IMPORTED)\n";
1040 case cmStateEnums::SHARED_LIBRARY:
1041 os << "add_library(" << targetName << " SHARED IMPORTED)\n";
1043 case cmStateEnums::MODULE_LIBRARY:
1044 os << "add_library(" << targetName << " MODULE IMPORTED)\n";
1046 case cmStateEnums::UNKNOWN_LIBRARY:
1047 os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
1049 case cmStateEnums::OBJECT_LIBRARY:
1050 os << "add_library(" << targetName << " OBJECT IMPORTED)\n";
1052 case cmStateEnums::INTERFACE_LIBRARY:
1053 os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
1055 default: // should never happen
1059 // Mark the imported executable if it has exports.
1060 if (target->IsExecutableWithExports()) {
1061 os << "set_property(TARGET " << targetName
1062 << " PROPERTY ENABLE_EXPORTS 1)\n";
1065 // Mark the imported library if it is a framework.
1066 if (target->IsFrameworkOnApple()) {
1067 os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
1070 // Mark the imported executable if it is an application bundle.
1071 if (target->IsAppBundleOnApple()) {
1072 os << "set_property(TARGET " << targetName
1073 << " PROPERTY MACOSX_BUNDLE 1)\n";
1076 if (target->IsCFBundleOnApple()) {
1077 os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
1080 // generate DEPRECATION
1081 if (target->IsDeprecated()) {
1082 os << "set_property(TARGET " << targetName << " PROPERTY DEPRECATION "
1083 << cmExportFileGeneratorEscape(target->GetDeprecation()) << ")\n";
1086 if (target->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
1087 os << "set_property(TARGET " << targetName
1088 << " PROPERTY IMPORTED_NO_SYSTEM 1)\n";
1094 void cmExportFileGenerator::GenerateImportPropertyCode(
1095 std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
1096 ImportPropertyMap const& properties)
1098 // Construct the imported target name.
1099 std::string targetName = this->Namespace;
1101 targetName += target->GetExportName();
1103 // Set the import properties.
1104 os << "# Import target \"" << targetName << "\" for configuration \""
1105 << config << "\"\n";
1106 os << "set_property(TARGET " << targetName
1107 << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
1108 if (!config.empty()) {
1109 os << cmSystemTools::UpperCase(config);
1114 os << "set_target_properties(" << targetName << " PROPERTIES\n";
1115 for (auto const& property : properties) {
1116 os << " " << property.first << " "
1117 << cmExportFileGeneratorEscape(property.second) << "\n";
1123 void cmExportFileGenerator::GenerateMissingTargetsCheckCode(std::ostream& os)
1125 if (this->MissingTargets.empty()) {
1126 /* clang-format off */
1127 os << "# This file does not depend on other imported targets which have\n"
1128 "# been exported from the same project but in a separate "
1130 /* clang-format on */
1133 /* clang-format off */
1134 os << "# Make sure the targets which have been exported in some other\n"
1135 "# export set exist.\n"
1136 "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1138 /* clang-format on */
1139 std::set<std::string> emitted;
1140 for (std::string const& missingTarget : this->MissingTargets) {
1141 if (emitted.insert(missingTarget).second) {
1142 os << "\"" << missingTarget << "\" ";
1145 /* clang-format off */
1147 " if(NOT TARGET \"${_target}\" )\n"
1148 " set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
1149 "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
1154 "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1155 " if(CMAKE_FIND_PACKAGE_NAME)\n"
1156 " set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
1157 " set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
1158 "\"The following imported targets are "
1159 "referenced, but are missing: "
1160 "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1162 " message(FATAL_ERROR \"The following imported targets are "
1163 "referenced, but are missing: "
1164 "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1167 "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1169 /* clang-format on */
1172 void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
1174 // Add code which verifies at cmake time that the file which is being
1175 // imported actually exists on disk. This should in theory always be theory
1176 // case, but still when packages are split into normal and development
1177 // packages this might get broken (e.g. the Config.cmake could be part of
1178 // the non-development package, something similar happened to me without
1179 // on SUSE with a mysql pkg-config file, which claimed everything is fine,
1180 // but the development package was not installed.).
1181 /* clang-format off */
1182 os << "# Loop over all imported files and verify that they actually exist\n"
1183 "foreach(_cmake_target IN LISTS _cmake_import_check_targets)\n"
1184 " foreach(_cmake_file IN LISTS \"_cmake_import_check_files_for_${_cmake_target}\")\n"
1185 " if(NOT EXISTS \"${_cmake_file}\")\n"
1186 " message(FATAL_ERROR \"The imported target \\\"${_cmake_target}\\\""
1187 " references the file\n"
1188 " \\\"${_cmake_file}\\\"\n"
1189 "but this file does not exist. Possible reasons include:\n"
1190 "* The file was deleted, renamed, or moved to another location.\n"
1191 "* An install or uninstall procedure did not complete successfully.\n"
1192 "* The installation package was faulty and contained\n"
1193 " \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
1194 "but not all the files it references.\n"
1198 " unset(_cmake_file)\n"
1199 " unset(\"_cmake_import_check_files_for_${_cmake_target}\")\n"
1201 "unset(_cmake_target)\n"
1202 "unset(_cmake_import_check_targets)\n"
1204 /* clang-format on */
1207 void cmExportFileGenerator::GenerateImportedFileChecksCode(
1208 std::ostream& os, cmGeneratorTarget* target,
1209 ImportPropertyMap const& properties,
1210 const std::set<std::string>& importedLocations)
1212 // Construct the imported target name.
1213 std::string targetName = cmStrCat(this->Namespace, target->GetExportName());
1215 os << "list(APPEND _cmake_import_check_targets " << targetName
1217 "list(APPEND _cmake_import_check_files_for_"
1218 << targetName << " ";
1220 for (std::string const& li : importedLocations) {
1221 auto pi = properties.find(li);
1222 if (pi != properties.end()) {
1223 os << cmExportFileGeneratorEscape(pi->second) << " ";
1230 bool cmExportFileGenerator::PopulateExportProperties(
1231 cmGeneratorTarget const* gte, ImportPropertyMap& properties,
1232 std::string& errorMessage)
1234 const auto& targetProperties = gte->Target->GetProperties();
1235 if (cmValue exportProperties =
1236 targetProperties.GetPropertyValue("EXPORT_PROPERTIES")) {
1237 for (auto& prop : cmExpandedList(*exportProperties)) {
1238 /* Black list reserved properties */
1239 if (cmHasLiteralPrefix(prop, "IMPORTED_") ||
1240 cmHasLiteralPrefix(prop, "INTERFACE_")) {
1241 std::ostringstream e;
1242 e << "Target \"" << gte->Target->GetName() << "\" contains property \""
1243 << prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* "
1244 << "properties are reserved.";
1245 errorMessage = e.str();
1248 cmValue propertyValue = targetProperties.GetPropertyValue(prop);
1249 if (!propertyValue) {
1250 // Asked to export a property that isn't defined on the target. Do not
1251 // consider this an error, there's just nothing to export.
1254 std::string evaluatedValue = cmGeneratorExpression::Preprocess(
1255 *propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions);
1256 if (evaluatedValue != *propertyValue) {
1257 std::ostringstream e;
1258 e << "Target \"" << gte->Target->GetName() << "\" contains property \""
1259 << prop << "\" in EXPORT_PROPERTIES but this property contains a "
1260 << "generator expression. This is not allowed.";
1261 errorMessage = e.str();
1264 properties[prop] = *propertyValue;
1270 void cmExportFileGenerator::GenerateTargetFileSets(cmGeneratorTarget* gte,
1274 auto interfaceFileSets = gte->Target->GetAllInterfaceFileSets();
1275 if (!interfaceFileSets.empty()) {
1276 std::string targetName = cmStrCat(this->Namespace, gte->GetExportName());
1277 os << "if(NOT CMAKE_VERSION VERSION_LESS \"3.23.0\")\n"
1279 << targetName << "\n";
1281 for (auto const& name : interfaceFileSets) {
1282 auto* fileSet = gte->Target->GetFileSet(name);
1284 gte->Makefile->IssueMessage(
1285 MessageType::FATAL_ERROR,
1286 cmStrCat("File set \"", name,
1287 "\" is listed in interface file sets of ", gte->GetName(),
1288 " but has not been created"));
1293 << "\n FILE_SET " << cmOutputConverter::EscapeForCMake(name)
1295 << cmOutputConverter::EscapeForCMake(fileSet->GetType())
1297 << this->GetFileSetDirectories(gte, fileSet, te) << "\n FILES "
1298 << this->GetFileSetFiles(gte, fileSet, te) << "\n";
1301 os << " )\nendif()\n\n";