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 "cmVisualStudio10TargetGenerator.h"
13 #include <cm/optional>
14 #include <cm/string_view>
16 #include <cmext/algorithm>
20 #include "cmsys/FStream.hxx"
21 #include "cmsys/RegularExpression.hxx"
23 #include "cmComputeLinkInformation.h"
24 #include "cmCustomCommand.h"
25 #include "cmCustomCommandGenerator.h"
26 #include "cmGeneratedFileStream.h"
27 #include "cmGeneratorExpression.h"
28 #include "cmGeneratorTarget.h"
29 #include "cmGlobalGenerator.h"
30 #include "cmGlobalVisualStudio10Generator.h"
31 #include "cmGlobalVisualStudio7Generator.h"
32 #include "cmGlobalVisualStudioGenerator.h"
33 #include "cmLinkLineDeviceComputer.h"
34 #include "cmListFileCache.h"
35 #include "cmLocalGenerator.h"
36 #include "cmLocalVisualStudio10Generator.h"
37 #include "cmLocalVisualStudio7Generator.h"
38 #include "cmLocalVisualStudioGenerator.h"
39 #include "cmMakefile.h"
40 #include "cmMessageType.h"
41 #include "cmPropertyMap.h"
42 #include "cmSourceFile.h"
43 #include "cmSourceFileLocation.h"
44 #include "cmSourceFileLocationKind.h"
45 #include "cmSourceGroup.h"
46 #include "cmStateTypes.h"
47 #include "cmStringAlgorithms.h"
48 #include "cmSystemTools.h"
51 #include "cmVisualStudioGeneratorOptions.h"
53 struct cmIDEFlagTable;
55 static void ConvertToWindowsSlash(std::string& s);
57 static std::string cmVS10EscapeXML(std::string arg)
59 cmSystemTools::ReplaceString(arg, "&", "&");
60 cmSystemTools::ReplaceString(arg, "<", "<");
61 cmSystemTools::ReplaceString(arg, ">", ">");
65 static std::string cmVS10EscapeAttr(std::string arg)
67 cmSystemTools::ReplaceString(arg, "&", "&");
68 cmSystemTools::ReplaceString(arg, "<", "<");
69 cmSystemTools::ReplaceString(arg, ">", ">");
70 cmSystemTools::ReplaceString(arg, "\"", """);
71 cmSystemTools::ReplaceString(arg, "\n", " ");
75 struct cmVisualStudio10TargetGenerator::Elem
79 bool HasElements = false;
80 bool HasContent = false;
83 Elem(std::ostream& s, const std::string& tag)
90 Elem(const Elem&) = delete;
91 Elem(Elem& par, cm::string_view tag)
93 , Indent(par.Indent + 1)
94 , Tag(std::string(tag))
106 std::ostream& WriteString(const char* line);
107 void StartElement() { this->WriteString("<") << this->Tag; }
108 void Element(cm::string_view tag, std::string val)
110 Elem(*this, tag).Content(std::move(val));
112 Elem& Attribute(const char* an, std::string av)
114 this->S << " " << an << "=\"" << cmVS10EscapeAttr(std::move(av)) << "\"";
117 void Content(std::string val)
119 if (!this->HasContent) {
121 this->HasContent = true;
123 this->S << cmVS10EscapeXML(std::move(val));
127 // Do not emit element which has not been started
133 this->WriteString("</") << this->Tag << ">";
134 } else if (HasContent) {
135 this->S << "</" << this->Tag << ">";
141 void WritePlatformConfigTag(const std::string& tag, const std::string& cond,
142 const std::string& content);
145 class cmVS10GeneratorOptions : public cmVisualStudioGeneratorOptions
148 using Elem = cmVisualStudio10TargetGenerator::Elem;
149 cmVS10GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool,
150 cmVS7FlagTable const* table,
151 cmVisualStudio10TargetGenerator* g = nullptr)
152 : cmVisualStudioGeneratorOptions(lg, tool, table)
157 void OutputFlag(std::ostream& /*fout*/, int /*indent*/,
158 const std::string& tag, const std::string& content) override
160 if (!this->GetConfiguration().empty()) {
161 // if there are configuration specific flags, then
162 // use the configuration specific tag for PreprocessorDefinitions
163 const std::string cond =
164 this->TargetGenerator->CalcCondition(this->GetConfiguration());
165 this->Parent->WritePlatformConfigTag(tag, cond, content);
167 this->Parent->Element(tag, content);
172 cmVisualStudio10TargetGenerator* const TargetGenerator;
173 Elem* Parent = nullptr;
174 friend cmVisualStudio10TargetGenerator::OptionsHelper;
177 struct cmVisualStudio10TargetGenerator::OptionsHelper
179 cmVS10GeneratorOptions& O;
180 OptionsHelper(cmVS10GeneratorOptions& o, Elem& e)
185 ~OptionsHelper() { O.Parent = nullptr; }
187 void OutputPreprocessorDefinitions(const std::string& lang)
189 O.OutputPreprocessorDefinitions(O.Parent->S, O.Parent->Indent + 1, lang);
191 void OutputAdditionalIncludeDirectories(const std::string& lang)
193 O.OutputAdditionalIncludeDirectories(O.Parent->S, O.Parent->Indent + 1,
196 void OutputFlagMap() { O.OutputFlagMap(O.Parent->S, O.Parent->Indent + 1); }
197 void PrependInheritedString(std::string const& key)
199 O.PrependInheritedString(key);
203 static std::string cmVS10EscapeComment(std::string comment)
205 // MSBuild takes the CDATA of a <Message></Message> element and just
206 // does "echo $CDATA" with no escapes. We must encode the string.
207 // http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx
208 std::string echoable;
209 for (char c : comment) {
216 case '"': /* no break */
217 case '|': /* no break */
218 case '&': /* no break */
219 case '<': /* no break */
220 case '>': /* no break */
222 echoable += '^'; /* no break */
232 static bool cmVS10IsTargetsFile(std::string const& path)
234 std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
235 return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
238 static VsProjectType computeProjectType(cmGeneratorTarget const* t)
240 if (t->IsCSharpOnly()) {
241 return VsProjectType::csproj;
243 return VsProjectType::vcxproj;
246 static std::string computeProjectFileExtension(VsProjectType projectType)
248 switch (projectType) {
249 case VsProjectType::csproj:
251 case VsProjectType::proj:
258 static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
260 return computeProjectFileExtension(computeProjectType(t));
263 cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
264 cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
265 : GeneratorTarget(target)
266 , Makefile(target->Target->GetMakefile())
267 , Platform(gg->GetPlatformName())
268 , Name(target->GetName())
269 , GUID(gg->GetGUID(this->Name))
270 , GlobalGenerator(gg)
272 (cmLocalVisualStudio10Generator*)target->GetLocalGenerator())
274 this->Configurations =
275 this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
276 this->NsightTegra = gg->IsNsightTegra();
277 this->Android = gg->TargetsAndroid();
278 for (int i = 0; i < 4; ++i) {
279 this->NsightTegraVersion[i] = 0;
281 sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
282 &this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
283 &this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
284 this->MSTools = !this->NsightTegra && !this->Android;
285 this->Managed = false;
286 this->TargetCompileAsWinRT = false;
287 this->IsMissingFiles = false;
288 this->DefaultArtifactDir =
289 this->LocalGenerator->GetCurrentBinaryDirectory() + "/" +
290 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
291 this->InSourceBuild = (this->Makefile->GetCurrentSourceDirectory() ==
292 this->Makefile->GetCurrentBinaryDirectory());
293 this->ClassifyAllConfigSources();
296 cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
300 std::string cmVisualStudio10TargetGenerator::CalcCondition(
301 const std::string& config) const
303 std::ostringstream oss;
304 oss << "'$(Configuration)|$(Platform)'=='";
305 oss << config << "|" << this->Platform;
307 // handle special case for 32 bit C# targets
308 if (this->ProjectType == VsProjectType::csproj &&
309 this->Platform == "Win32") {
311 oss << "'$(Configuration)|$(Platform)'=='";
312 oss << config << "|x86";
318 void cmVisualStudio10TargetGenerator::Elem::WritePlatformConfigTag(
319 const std::string& tag, const std::string& cond, const std::string& content)
321 Elem(*this, tag).Attribute("Condition", cond).Content(content);
324 std::ostream& cmVisualStudio10TargetGenerator::Elem::WriteString(
329 this->S.width(this->Indent * 2);
330 // write an empty string to get the fill level indent to print
336 #define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
337 #define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
338 #define VS10_CXX_USER_PROPS \
339 "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
340 #define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
342 #define VS10_CSharp_DEFAULT_PROPS \
343 "$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
344 // This does not seem to exist by default, it's just provided for consistency
345 // in case users want to have default custom props for C# targets
346 #define VS10_CSharp_USER_PROPS \
347 "$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
348 #define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
350 #define VS10_CSharp_NETCF_TARGETS \
351 "$(MSBuildExtensionsPath)\\Microsoft\\$(TargetFrameworkIdentifier)\\" \
352 "$(TargetFrameworkTargetsVersion)\\Microsoft.$(TargetFrameworkIdentifier)" \
355 void cmVisualStudio10TargetGenerator::Generate()
357 this->ProjectType = computeProjectType(this->GeneratorTarget);
358 this->Managed = this->ProjectType == VsProjectType::csproj;
359 const std::string ProjectFileExtension =
360 computeProjectFileExtension(this->ProjectType);
362 if (this->ProjectType == VsProjectType::csproj &&
363 this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
364 std::string message = "The C# target \"" +
365 this->GeneratorTarget->GetName() +
366 "\" is of type STATIC_LIBRARY. This is discouraged (and may be "
367 "disabled in future). Make it a SHARED library instead.";
368 this->Makefile->IssueMessage(MessageType::DEPRECATION_WARNING, message);
372 this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE &&
373 !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
374 this->GlobalGenerator->AddAndroidExecutableWarning(this->Name);
377 // Tell the global generator the name of the project file
378 this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
380 this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
381 ProjectFileExtension);
382 this->DotNetHintReferences.clear();
383 this->AdditionalUsingDirectories.clear();
384 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
385 if (!this->ComputeClOptions()) {
388 if (!this->ComputeRcOptions()) {
391 if (!this->ComputeCudaOptions()) {
394 if (!this->ComputeCudaLinkOptions()) {
397 if (!this->ComputeMasmOptions()) {
400 if (!this->ComputeNasmOptions()) {
403 if (!this->ComputeLinkOptions()) {
406 if (!this->ComputeLibOptions()) {
411 cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
412 this->Name, ProjectFileExtension);
413 cmGeneratedFileStream BuildFileStream(path);
414 const std::string PathToProjectFile = path;
415 BuildFileStream.SetCopyIfDifferent(true);
417 // Write the encoding header into the file
418 char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
419 BuildFileStream.write(magic, 3);
421 if (this->ProjectType == VsProjectType::csproj &&
422 this->GeneratorTarget->IsDotNetSdkTarget() &&
423 this->GlobalGenerator->GetVersion() >=
424 cmGlobalVisualStudioGenerator::VSVersion::VS16) {
425 this->WriteSdkStyleProjectFile(BuildFileStream);
427 this->WriteClassicMsBuildProjectFile(BuildFileStream);
430 if (BuildFileStream.Close()) {
431 this->GlobalGenerator->FileReplacedDuringGenerate(PathToProjectFile);
434 // The groups are stored in a separate file for VS 10
437 // Update cache with project-specific entries.
441 void cmVisualStudio10TargetGenerator::WriteClassicMsBuildProjectFile(
442 cmGeneratedFileStream& BuildFileStream)
444 BuildFileStream << "<?xml version=\"1.0\" encoding=\""
445 << this->GlobalGenerator->Encoding() << "\"?>";
447 Elem e0(BuildFileStream, "Project");
448 e0.Attribute("DefaultTargets", "Build");
449 const char* toolsVersion = this->GlobalGenerator->GetToolsVersion();
450 if (this->GlobalGenerator->GetVersion() ==
451 cmGlobalVisualStudioGenerator::VSVersion::VS12 &&
452 this->GlobalGenerator->TargetsWindowsCE()) {
453 toolsVersion = "4.0";
455 e0.Attribute("ToolsVersion", toolsVersion);
456 e0.Attribute("xmlns",
457 "http://schemas.microsoft.com/developer/msbuild/2003");
459 if (this->NsightTegra) {
460 Elem e1(e0, "PropertyGroup");
461 e1.Attribute("Label", "NsightTegraProject");
462 const unsigned int nsightTegraMajorVersion = this->NsightTegraVersion[0];
463 const unsigned int nsightTegraMinorVersion = this->NsightTegraVersion[1];
464 if (nsightTegraMajorVersion >= 2) {
465 if (nsightTegraMajorVersion > 3 ||
466 (nsightTegraMajorVersion == 3 && nsightTegraMinorVersion >= 1)) {
467 e1.Element("NsightTegraProjectRevisionNumber", "11");
469 // Nsight Tegra 2.0 uses project revision 9.
470 e1.Element("NsightTegraProjectRevisionNumber", "9");
472 // Tell newer versions to upgrade silently when loading.
473 e1.Element("NsightTegraUpgradeOnceWithoutPrompt", "true");
475 // Require Nsight Tegra 1.6 for JCompile support.
476 e1.Element("NsightTegraProjectRevisionNumber", "7");
480 if (const char* hostArch =
481 this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
482 Elem e1(e0, "PropertyGroup");
483 e1.Element("PreferredToolArchitecture", hostArch);
486 // ALL_BUILD and ZERO_CHECK projects transitively include
487 // Microsoft.Common.CurrentVersion.targets which triggers Target
488 // ResolveNugetPackageAssets when SDK-style targets are in the project.
489 // However, these projects have no nuget packages to reference and the
491 // Setting ResolveNugetPackages to false skips this target and the build
493 cm::string_view targetName{ this->GeneratorTarget->GetName() };
494 if (targetName == "ALL_BUILD" ||
495 targetName == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
496 Elem e1(e0, "PropertyGroup");
497 e1.Element("ResolveNugetPackages", "false");
500 if (this->ProjectType != VsProjectType::csproj) {
501 this->WriteProjectConfigurations(e0);
505 Elem e1(e0, "PropertyGroup");
506 this->WriteCommonPropertyGroupGlobals(e1);
508 if ((this->MSTools || this->Android) &&
509 this->GeneratorTarget->IsInBuildSystem()) {
510 this->WriteApplicationTypeSettings(e1);
511 this->VerifyNecessaryFiles();
514 cmValue vsProjectName =
515 this->GeneratorTarget->GetProperty("VS_SCC_PROJECTNAME");
516 cmValue vsLocalPath =
517 this->GeneratorTarget->GetProperty("VS_SCC_LOCALPATH");
519 this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER");
521 if (vsProjectName && vsLocalPath && vsProvider) {
522 e1.Element("SccProjectName", *vsProjectName);
523 e1.Element("SccLocalPath", *vsLocalPath);
524 e1.Element("SccProvider", *vsProvider);
527 this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH");
529 e1.Element("SccAuxPath", *vsAuxPath);
533 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
534 e1.Element("WinMDAssembly", "true");
537 e1.Element("Platform", this->Platform);
538 cmValue projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL");
539 e1.Element("ProjectName", projLabel ? projLabel : this->Name);
541 cm::optional<std::string> targetFramework;
542 cm::optional<std::string> targetFrameworkVersion;
543 cm::optional<std::string> targetFrameworkIdentifier;
544 cm::optional<std::string> targetFrameworkTargetsVersion;
546 this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK")) {
547 targetFramework = *tf;
548 } else if (cmValue vstfVer = this->GeneratorTarget->GetProperty(
549 "VS_DOTNET_TARGET_FRAMEWORK_VERSION")) {
550 // FIXME: Someday, add a deprecation warning for VS_* property.
551 targetFrameworkVersion = *vstfVer;
552 } else if (cmValue tfVer = this->GeneratorTarget->GetProperty(
553 "DOTNET_TARGET_FRAMEWORK_VERSION")) {
554 targetFrameworkVersion = *tfVer;
555 } else if (this->ProjectType == VsProjectType::csproj) {
556 targetFrameworkVersion =
557 this->GlobalGenerator->GetTargetFrameworkVersion();
559 if (this->ProjectType == VsProjectType::vcxproj &&
560 this->GlobalGenerator->TargetsWindowsCE()) {
561 e1.Element("EnableRedirectPlatform", "true");
562 e1.Element("RedirectPlatformValue", this->Platform);
564 if (this->ProjectType == VsProjectType::csproj) {
565 if (this->GlobalGenerator->TargetsWindowsCE()) {
566 // FIXME: These target VS_TARGET_FRAMEWORK* target properties
567 // are undocumented settings only ever supported for WinCE.
568 // We need a better way to control these in general.
569 if (cmValue tfId = this->GeneratorTarget->GetProperty(
570 "VS_TARGET_FRAMEWORK_IDENTIFIER")) {
571 targetFrameworkIdentifier = *tfId;
573 if (cmValue tfTargetsVer = this->GeneratorTarget->GetProperty(
574 "VS_TARGET_FRAMEWORKS_TARGET_VERSION")) {
575 targetFrameworkTargetsVersion = *tfTargetsVer;
578 if (!targetFrameworkIdentifier) {
579 targetFrameworkIdentifier =
580 this->GlobalGenerator->GetTargetFrameworkIdentifier();
582 if (!targetFrameworkTargetsVersion) {
583 targetFrameworkTargetsVersion =
584 this->GlobalGenerator->GetTargetFrameworkTargetsVersion();
587 if (targetFramework) {
588 if (targetFramework->find(';') != std::string::npos) {
589 e1.Element("TargetFrameworks", *targetFramework);
591 e1.Element("TargetFramework", *targetFramework);
594 if (targetFrameworkVersion) {
595 e1.Element("TargetFrameworkVersion", *targetFrameworkVersion);
597 if (targetFrameworkIdentifier) {
598 e1.Element("TargetFrameworkIdentifier", *targetFrameworkIdentifier);
600 if (targetFrameworkTargetsVersion) {
601 e1.Element("TargetFrameworkTargetsVersion",
602 *targetFrameworkTargetsVersion);
604 if (!this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString()
607 "CudaToolkitCustomDir",
608 this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString() +
609 this->GlobalGenerator->GetPlatformToolsetCudaNvccSubdirString());
613 // Disable the project upgrade prompt that is displayed the first time a
614 // project using an older toolset version is opened in a newer version of
615 // the IDE (respected by VS 2013 and above).
616 if (this->GlobalGenerator->GetVersion() >=
617 cmGlobalVisualStudioGenerator::VSVersion::VS12) {
618 e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
621 if (const char* vcTargetsPath =
622 this->GlobalGenerator->GetCustomVCTargetsPath()) {
623 e1.Element("VCTargetsPath", vcTargetsPath);
627 if (this->LocalGenerator->GetVersion() >=
628 cmGlobalVisualStudioGenerator::VSVersion::VS17) {
629 e1.Element("ManagedAssembly", "true");
631 std::string outputType;
632 switch (this->GeneratorTarget->GetType()) {
633 case cmStateEnums::OBJECT_LIBRARY:
634 case cmStateEnums::STATIC_LIBRARY:
635 case cmStateEnums::SHARED_LIBRARY:
636 outputType = "Library";
638 case cmStateEnums::MODULE_LIBRARY:
639 outputType = "Module";
641 case cmStateEnums::EXECUTABLE: {
643 this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
644 if (win32.find("$<") != std::string::npos) {
645 this->Makefile->IssueMessage(
646 MessageType::FATAL_ERROR,
648 "Target \"", this->GeneratorTarget->GetName(),
649 "\" has a generator expression in its WIN32_EXECUTABLE "
650 "property. This is not supported on managed executables."));
654 outputType = "WinExe";
659 case cmStateEnums::UTILITY:
660 case cmStateEnums::INTERFACE_LIBRARY:
661 case cmStateEnums::GLOBAL_TARGET:
662 outputType = "Utility";
664 case cmStateEnums::UNKNOWN_LIBRARY:
667 e1.Element("OutputType", outputType);
668 e1.Element("AppDesignerFolder", "Properties");
672 cmValue startupObject =
673 this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
675 if (startupObject && this->Managed) {
676 Elem e1(e0, "PropertyGroup");
677 e1.Element("StartupObject", *startupObject);
680 switch (this->ProjectType) {
681 case VsProjectType::vcxproj: {
682 std::string const& props =
683 this->GlobalGenerator->GetPlatformToolsetVersionProps();
684 if (!props.empty()) {
685 Elem(e0, "Import").Attribute("Project", props);
687 Elem(e0, "Import").Attribute("Project", VS10_CXX_DEFAULT_PROPS);
689 case VsProjectType::csproj:
691 .Attribute("Project", VS10_CSharp_DEFAULT_PROPS)
692 .Attribute("Condition", "Exists('" VS10_CSharp_DEFAULT_PROPS "')");
698 this->WriteProjectConfigurationValues(e0);
700 if (this->ProjectType == VsProjectType::vcxproj) {
701 Elem(e0, "Import").Attribute("Project", VS10_CXX_PROPS);
704 Elem e1(e0, "ImportGroup");
705 e1.Attribute("Label", "ExtensionSettings");
708 if (this->GlobalGenerator->IsCudaEnabled()) {
710 this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
711 std::string cudaPath = customDir.empty()
712 ? "$(VCTargetsPath)\\BuildCustomizations\\"
714 this->GlobalGenerator
715 ->GetPlatformToolsetCudaVSIntegrationSubdirString() +
716 "extras\\visual_studio_integration\\MSBuildExtensions\\";
718 .Attribute("Project",
719 std::move(cudaPath) + "CUDA " +
720 this->GlobalGenerator->GetPlatformToolsetCuda() +
723 if (this->GlobalGenerator->IsMasmEnabled()) {
725 .Attribute("Project",
726 "$(VCTargetsPath)\\BuildCustomizations\\masm.props");
728 if (this->GlobalGenerator->IsNasmEnabled()) {
729 // Always search in the standard modules location.
730 std::string propsTemplate =
731 GetCMakeFilePath("Templates/MSBuild/nasm.props.in");
733 std::string propsLocal =
734 cmStrCat(this->DefaultArtifactDir, "\\nasm.props");
735 ConvertToWindowsSlash(propsLocal);
736 this->Makefile->ConfigureFile(propsTemplate, propsLocal, false, true,
738 Elem(e1, "Import").Attribute("Project", propsLocal);
742 Elem e1(e0, "ImportGroup");
743 e1.Attribute("Label", "PropertySheets");
745 switch (this->ProjectType) {
746 case VsProjectType::vcxproj:
747 props = VS10_CXX_USER_PROPS;
749 case VsProjectType::csproj:
750 props = VS10_CSharp_USER_PROPS;
755 if (cmValue p = this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
758 if (!props.empty()) {
759 ConvertToWindowsSlash(props);
761 .Attribute("Project", props)
762 .Attribute("Condition", "exists('" + props + "')")
763 .Attribute("Label", "LocalAppDataPlatform");
766 this->WritePlatformExtensions(e1);
769 this->WriteDotNetDocumentationFile(e0);
770 Elem(e0, "PropertyGroup").Attribute("Label", "UserMacros");
771 this->WriteWinRTPackageCertificateKeyFile(e0);
772 this->WritePathAndIncrementalLinkOptions(e0);
773 this->WriteCEDebugProjectConfigurationValues(e0);
774 this->WriteItemDefinitionGroups(e0);
775 this->WriteCustomCommands(e0);
776 this->WriteAllSources(e0);
777 this->WriteDotNetReferences(e0);
778 this->WritePackageReferences(e0);
779 this->WriteImports(e0);
780 this->WriteEmbeddedResourceGroup(e0);
781 this->WriteXamlFilesGroup(e0);
782 this->WriteWinRTReferences(e0);
783 this->WriteProjectReferences(e0);
784 this->WriteSDKReferences(e0);
785 switch (this->ProjectType) {
786 case VsProjectType::vcxproj:
787 Elem(e0, "Import").Attribute("Project", VS10_CXX_TARGETS);
789 case VsProjectType::csproj:
790 if (this->GlobalGenerator->TargetsWindowsCE()) {
791 Elem(e0, "Import").Attribute("Project", VS10_CSharp_NETCF_TARGETS);
793 Elem(e0, "Import").Attribute("Project", VS10_CSharp_TARGETS);
800 this->WriteTargetSpecificReferences(e0);
802 Elem e1(e0, "ImportGroup");
803 e1.Attribute("Label", "ExtensionTargets");
805 this->WriteTargetsFileReferences(e1);
806 if (this->GlobalGenerator->IsCudaEnabled()) {
808 this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
809 std::string cudaPath = customDir.empty()
810 ? "$(VCTargetsPath)\\BuildCustomizations\\"
812 this->GlobalGenerator
813 ->GetPlatformToolsetCudaVSIntegrationSubdirString() +
814 "extras\\visual_studio_integration\\MSBuildExtensions\\";
816 .Attribute("Project",
817 std::move(cudaPath) + "CUDA " +
818 this->GlobalGenerator->GetPlatformToolsetCuda() +
821 if (this->GlobalGenerator->IsMasmEnabled()) {
823 .Attribute("Project",
824 "$(VCTargetsPath)\\BuildCustomizations\\masm.targets");
826 if (this->GlobalGenerator->IsNasmEnabled()) {
827 std::string nasmTargets =
828 GetCMakeFilePath("Templates/MSBuild/nasm.targets");
829 Elem(e1, "Import").Attribute("Project", nasmTargets);
832 if (this->ProjectType == VsProjectType::vcxproj &&
833 this->HaveCustomCommandDepfile) {
834 std::string depfileTargets =
835 GetCMakeFilePath("Templates/MSBuild/CustomBuildDepFile.targets");
836 Elem(e0, "Import").Attribute("Project", depfileTargets);
838 if (this->ProjectType == VsProjectType::csproj) {
839 for (std::string const& c : this->Configurations) {
840 Elem e1(e0, "PropertyGroup");
841 e1.Attribute("Condition", "'$(Configuration)' == '" + c + "'");
843 this->WriteEvents(e1, c);
845 // make sure custom commands are executed before build (if necessary)
847 Elem e1(e0, "PropertyGroup");
848 std::ostringstream oss;
850 for (std::string const& i : this->CSharpCustomCommandNames) {
851 oss << " " << i << ";\n";
854 << "$(BuildDependsOn)\n";
855 e1.Element("BuildDependsOn", oss.str());
861 void cmVisualStudio10TargetGenerator::WriteSdkStyleProjectFile(
862 cmGeneratedFileStream& BuildFileStream)
864 if (this->ProjectType != VsProjectType::csproj ||
865 !this->GeneratorTarget->IsDotNetSdkTarget()) {
866 std::string message = "The target \"" + this->GeneratorTarget->GetName() +
867 "\" is not eligible for .Net SDK style project.";
868 this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
872 if (this->HasCustomCommands()) {
873 std::string message = "The target \"" + this->GeneratorTarget->GetName() +
874 "\" does not currently support add_custom_command as the Visual Studio "
875 "generators have not yet learned how to generate custom commands in "
876 ".Net SDK-style projects.";
877 this->Makefile->IssueMessage(MessageType::FATAL_ERROR, message);
881 Elem e0(BuildFileStream, "Project");
882 e0.Attribute("Sdk", *this->GeneratorTarget->GetProperty("DOTNET_SDK"));
885 Elem e1(e0, "PropertyGroup");
886 this->WriteCommonPropertyGroupGlobals(e1);
888 e1.Element("EnableDefaultItems", "false");
889 // Disable the project upgrade prompt that is displayed the first time a
890 // project using an older toolset version is opened in a newer version
892 e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
893 e1.Element("ManagedAssembly", "true");
895 cmValue targetFramework =
896 this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK");
897 if (targetFramework) {
898 if (targetFramework->find(';') != std::string::npos) {
899 e1.Element("TargetFrameworks", *targetFramework);
901 e1.Element("TargetFramework", *targetFramework);
904 e1.Element("TargetFramework", "net5.0");
907 std::string outputType;
908 switch (this->GeneratorTarget->GetType()) {
909 case cmStateEnums::OBJECT_LIBRARY:
910 case cmStateEnums::STATIC_LIBRARY:
911 case cmStateEnums::MODULE_LIBRARY:
912 this->Makefile->IssueMessage(
913 MessageType::FATAL_ERROR,
914 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
915 "\" is of a type not supported for managed binaries."));
917 case cmStateEnums::SHARED_LIBRARY:
918 outputType = "Library";
920 case cmStateEnums::EXECUTABLE: {
922 this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
923 if (win32.find("$<") != std::string::npos) {
924 this->Makefile->IssueMessage(
925 MessageType::FATAL_ERROR,
926 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
927 "\" has a generator expression in its WIN32_EXECUTABLE "
928 "property. This is not supported on managed "
934 case cmStateEnums::UTILITY:
935 case cmStateEnums::INTERFACE_LIBRARY:
936 case cmStateEnums::GLOBAL_TARGET:
937 outputType = "Utility";
939 case cmStateEnums::UNKNOWN_LIBRARY:
942 e1.Element("OutputType", outputType);
944 cmValue startupObject =
945 this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
947 e1.Element("StartupObject", *startupObject);
951 for (const std::string& config : this->Configurations) {
952 Elem e1(e0, "PropertyGroup");
953 e1.Attribute("Condition", "'$(Configuration)' == '" + config + "'");
955 this->WriteEvents(e1, config);
957 std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
958 ConvertToWindowsSlash(outDir);
959 e1.Element("OutputPath", outDir);
962 this->WriteDotNetDocumentationFile(e0);
963 this->WriteAllSources(e0);
964 this->WriteDotNetReferences(e0);
965 this->WritePackageReferences(e0);
966 this->WriteProjectReferences(e0);
969 void cmVisualStudio10TargetGenerator::WriteCommonPropertyGroupGlobals(Elem& e1)
971 e1.Attribute("Label", "Globals");
972 e1.Element("ProjectGuid", "{" + this->GUID + "}");
974 cmValue vsProjectTypes =
975 this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
976 if (vsProjectTypes) {
977 const char* tagName = "ProjectTypes";
978 if (this->ProjectType == VsProjectType::csproj) {
979 tagName = "ProjectTypeGuids";
981 e1.Element(tagName, *vsProjectTypes);
984 cmValue vsGlobalKeyword =
985 this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD");
986 if (!vsGlobalKeyword) {
987 if (this->GlobalGenerator->TargetsAndroid()) {
988 e1.Element("Keyword", "Android");
990 e1.Element("Keyword", "Win32Proj");
993 e1.Element("Keyword", *vsGlobalKeyword);
996 cmValue vsGlobalRootNamespace =
997 this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE");
998 if (vsGlobalRootNamespace) {
999 e1.Element("RootNamespace", *vsGlobalRootNamespace);
1002 std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
1003 for (std::string const& keyIt : keys) {
1004 static const cm::string_view prefix = "VS_GLOBAL_";
1005 if (!cmHasPrefix(keyIt, prefix))
1007 cm::string_view globalKey = cm::string_view(keyIt).substr(prefix.length());
1008 // Skip invalid or separately-handled properties.
1009 if (globalKey.empty() || globalKey == "PROJECT_TYPES" ||
1010 globalKey == "ROOTNAMESPACE" || globalKey == "KEYWORD") {
1013 cmValue value = this->GeneratorTarget->GetProperty(keyIt);
1016 e1.Element(globalKey, *value);
1020 bool cmVisualStudio10TargetGenerator::HasCustomCommands() const
1022 if (!this->GeneratorTarget->GetPreBuildCommands().empty() ||
1023 !this->GeneratorTarget->GetPreLinkCommands().empty() ||
1024 !this->GeneratorTarget->GetPostBuildCommands().empty()) {
1028 for (cmGeneratorTarget::AllConfigSource const& si :
1029 this->GeneratorTarget->GetAllConfigSources()) {
1030 if (si.Source->GetCustomCommand()) {
1038 void cmVisualStudio10TargetGenerator::WritePackageReferences(Elem& e0)
1040 std::vector<std::string> packageReferences =
1041 this->GeneratorTarget->GetPackageReferences();
1043 if (!packageReferences.empty()) {
1044 Elem e1(e0, "ItemGroup");
1045 for (std::string const& ri : packageReferences) {
1046 size_t versionIndex = ri.find_last_of('_');
1047 if (versionIndex != std::string::npos) {
1048 Elem e2(e1, "PackageReference");
1049 e2.Attribute("Include", ri.substr(0, versionIndex));
1050 e2.Attribute("Version", ri.substr(versionIndex + 1));
1056 void cmVisualStudio10TargetGenerator::WriteDotNetReferences(Elem& e0)
1058 std::vector<std::string> references;
1059 if (cmValue vsDotNetReferences =
1060 this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
1061 cmExpandList(*vsDotNetReferences, references);
1063 cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
1064 for (auto const& i : props.GetList()) {
1065 static const cm::string_view vsDnRef = "VS_DOTNET_REFERENCE_";
1066 if (cmHasPrefix(i.first, vsDnRef)) {
1067 std::string path = i.second;
1068 if (!cmsys::SystemTools::FileIsFullPath(path)) {
1069 path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
1071 ConvertToWindowsSlash(path);
1072 this->DotNetHintReferences[""].emplace_back(
1073 DotNetHintReference(i.first.substr(vsDnRef.length()), path));
1076 if (!references.empty() || !this->DotNetHintReferences.empty()) {
1077 Elem e1(e0, "ItemGroup");
1078 for (std::string const& ri : references) {
1079 // if the entry from VS_DOTNET_REFERENCES is an existing file, generate
1080 // a new hint-reference and name it from the filename
1081 if (cmsys::SystemTools::FileExists(ri, true)) {
1083 cmsys::SystemTools::GetFilenameWithoutLastExtension(ri);
1084 std::string path = ri;
1085 ConvertToWindowsSlash(path);
1086 this->DotNetHintReferences[""].emplace_back(
1087 DotNetHintReference(name, path));
1089 this->WriteDotNetReference(e1, ri, "", "");
1092 for (const auto& h : this->DotNetHintReferences) {
1093 // DotNetHintReferences is also populated from AddLibraries().
1094 // The configuration specific hint references are added there.
1095 for (const auto& i : h.second) {
1096 this->WriteDotNetReference(e1, i.first, i.second, h.first);
1102 void cmVisualStudio10TargetGenerator::WriteDotNetReference(
1103 Elem& e1, std::string const& ref, std::string const& hint,
1104 std::string const& config)
1106 Elem e2(e1, "Reference");
1107 // If 'config' is not empty, the reference is only added for the given
1108 // configuration. This is used when referencing imported managed assemblies.
1109 // See also cmVisualStudio10TargetGenerator::AddLibraries().
1110 if (!config.empty()) {
1111 e2.Attribute("Condition", this->CalcCondition(config));
1113 e2.Attribute("Include", ref);
1114 e2.Element("CopyLocalSatelliteAssemblies", "true");
1115 e2.Element("ReferenceOutputAssembly", "true");
1116 if (!hint.empty()) {
1117 const char* privateReference = "True";
1118 if (cmValue value = this->GeneratorTarget->GetProperty(
1119 "VS_DOTNET_REFERENCES_COPY_LOCAL")) {
1120 if (cmIsOff(*value)) {
1121 privateReference = "False";
1124 e2.Element("Private", privateReference);
1125 e2.Element("HintPath", hint);
1127 this->WriteDotNetReferenceCustomTags(e2, ref);
1130 void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0)
1133 this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT");
1135 std::vector<std::string> argsSplit = cmExpandedList(*imports, false);
1136 for (auto& path : argsSplit) {
1137 if (!cmsys::SystemTools::FileIsFullPath(path)) {
1138 path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
1140 ConvertToWindowsSlash(path);
1141 Elem e1(e0, "Import");
1142 e1.Attribute("Project", path);
1147 void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
1148 Elem& e2, std::string const& ref)
1151 static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
1152 static const std::string refpropInfix = "_TAG_";
1153 const std::string refPropFullPrefix = refpropPrefix + ref + refpropInfix;
1154 using CustomTags = std::map<std::string, std::string>;
1156 cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
1157 for (const auto& i : props.GetList()) {
1158 if (cmHasPrefix(i.first, refPropFullPrefix) && !i.second.empty()) {
1159 tags[i.first.substr(refPropFullPrefix.length())] = i.second;
1162 for (auto const& tag : tags) {
1163 e2.Element(tag.first, tag.second);
1167 void cmVisualStudio10TargetGenerator::WriteDotNetDocumentationFile(Elem& e0)
1169 std::string const& documentationFile =
1170 this->GeneratorTarget->GetSafeProperty("VS_DOTNET_DOCUMENTATION_FILE");
1172 if (this->ProjectType == VsProjectType::csproj &&
1173 !documentationFile.empty()) {
1174 Elem e1(e0, "PropertyGroup");
1175 Elem e2(e1, "DocumentationFile");
1176 e2.Content(documentationFile);
1180 void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup(Elem& e0)
1182 if (!this->ResxObjs.empty()) {
1183 Elem e1(e0, "ItemGroup");
1184 std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
1185 ConvertToWindowsSlash(srcDir);
1186 for (cmSourceFile const* oi : this->ResxObjs) {
1187 std::string obj = oi->GetFullPath();
1188 ConvertToWindowsSlash(obj);
1189 bool useRelativePath = false;
1190 if (this->ProjectType == VsProjectType::csproj && this->InSourceBuild) {
1191 // If we do an in-source build and the resource file is in a
1193 // of the .csproj file, we have to use relative pathnames, otherwise
1194 // visual studio does not show the file in the IDE. Sorry.
1195 if (cmHasPrefix(obj, srcDir)) {
1196 obj = this->ConvertPath(obj, true);
1197 ConvertToWindowsSlash(obj);
1198 useRelativePath = true;
1201 Elem e2(e1, "EmbeddedResource");
1202 e2.Attribute("Include", obj);
1204 if (this->ProjectType != VsProjectType::csproj) {
1205 std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
1206 e2.Element("DependentUpon", hFileName);
1208 for (std::string const& c : this->Configurations) {
1210 if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
1211 // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
1212 this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
1213 s = "$(RootNamespace).";
1215 s += "%(Filename).resources";
1216 e2.WritePlatformConfigTag("LogicalName", this->CalcCondition(c), s);
1219 std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
1220 ConvertToWindowsSlash(binDir);
1221 // If the resource was NOT added using a relative path (which should
1222 // be the default), we have to provide a link here
1223 if (!useRelativePath) {
1224 std::string link = this->GetCSharpSourceLink(oi);
1226 link = cmsys::SystemTools::GetFilenameName(obj);
1228 e2.Element("Link", link);
1230 // Determine if this is a generated resource from a .Designer.cs file
1231 std::string designerResource =
1232 cmSystemTools::GetFilenamePath(oi->GetFullPath()) + "/" +
1233 cmSystemTools::GetFilenameWithoutLastExtension(oi->GetFullPath()) +
1235 if (cmsys::SystemTools::FileExists(designerResource)) {
1236 std::string generator = "PublicResXFileCodeGenerator";
1237 if (cmValue g = oi->GetProperty("VS_RESOURCE_GENERATOR")) {
1240 if (!generator.empty()) {
1241 e2.Element("Generator", generator);
1242 if (cmHasPrefix(designerResource, srcDir)) {
1243 designerResource.erase(0, srcDir.length());
1244 } else if (cmHasPrefix(designerResource, binDir)) {
1245 designerResource.erase(0, binDir.length());
1248 cmsys::SystemTools::GetFilenameName(designerResource);
1250 ConvertToWindowsSlash(designerResource);
1251 e2.Element("LastGenOutput", designerResource);
1254 const cmPropertyMap& props = oi->GetProperties();
1255 for (const std::string& p : props.GetKeys()) {
1256 static const cm::string_view propNamePrefix = "VS_CSHARP_";
1257 if (cmHasPrefix(p, propNamePrefix)) {
1258 cm::string_view tagName =
1259 cm::string_view(p).substr(propNamePrefix.length());
1260 if (!tagName.empty()) {
1261 cmValue value = props.GetPropertyValue(p);
1262 if (cmNonempty(value)) {
1263 e2.Element(tagName, *value);
1273 void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup(Elem& e0)
1275 if (!this->XamlObjs.empty()) {
1276 Elem e1(e0, "ItemGroup");
1277 for (cmSourceFile const* oi : this->XamlObjs) {
1278 std::string obj = oi->GetFullPath();
1279 std::string xamlType;
1280 cmValue xamlTypeProperty = oi->GetProperty("VS_XAML_TYPE");
1281 if (xamlTypeProperty) {
1282 xamlType = *xamlTypeProperty;
1287 Elem e2(e1, xamlType);
1288 this->WriteSource(e2, oi);
1289 e2.SetHasElements();
1290 e2.Element("SubType", "Designer");
1295 void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences(Elem& e0)
1297 if (this->MSTools) {
1298 if (this->GlobalGenerator->TargetsWindowsPhone() &&
1299 this->GlobalGenerator->GetSystemVersion() == "8.0") {
1301 .Attribute("Project",
1302 "$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
1303 "$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
1304 "$(TargetPlatformVersion).targets");
1309 void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences(Elem& e1)
1311 for (TargetsFileAndConfigs const& tac : this->TargetsFileAndConfigsVec) {
1312 std::ostringstream oss;
1313 oss << "Exists('" << tac.File << "')";
1314 if (!tac.Configs.empty()) {
1316 for (size_t j = 0; j < tac.Configs.size(); ++j) {
1320 oss << "'$(Configuration)'=='" << tac.Configs[j] << "'";
1326 .Attribute("Project", tac.File)
1327 .Attribute("Condition", oss.str());
1331 void cmVisualStudio10TargetGenerator::WriteWinRTReferences(Elem& e0)
1333 std::vector<std::string> references;
1334 if (cmValue vsWinRTReferences =
1335 this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) {
1336 cmExpandList(*vsWinRTReferences, references);
1339 if (this->GlobalGenerator->TargetsWindowsPhone() &&
1340 this->GlobalGenerator->GetSystemVersion() == "8.0" &&
1341 references.empty()) {
1342 references.push_back("platform.winmd");
1344 if (!references.empty()) {
1345 Elem e1(e0, "ItemGroup");
1346 for (std::string const& ri : references) {
1347 Elem e2(e1, "Reference");
1348 e2.Attribute("Include", ri);
1349 e2.Element("IsWinMDFile", "true");
1354 // ConfigurationType Application, Utility StaticLibrary DynamicLibrary
1356 void cmVisualStudio10TargetGenerator::WriteProjectConfigurations(Elem& e0)
1358 Elem e1(e0, "ItemGroup");
1359 e1.Attribute("Label", "ProjectConfigurations");
1360 for (std::string const& c : this->Configurations) {
1361 Elem e2(e1, "ProjectConfiguration");
1362 e2.Attribute("Include", c + "|" + this->Platform);
1363 e2.Element("Configuration", c);
1364 e2.Element("Platform", this->Platform);
1368 void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues(Elem& e0)
1370 for (std::string const& c : this->Configurations) {
1371 Elem e1(e0, "PropertyGroup");
1372 e1.Attribute("Condition", this->CalcCondition(c));
1373 e1.Attribute("Label", "Configuration");
1375 if (this->ProjectType != VsProjectType::csproj) {
1376 std::string configType;
1377 if (cmValue vsConfigurationType =
1378 this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
1379 configType = cmGeneratorExpression::Evaluate(*vsConfigurationType,
1380 this->LocalGenerator, c);
1382 switch (this->GeneratorTarget->GetType()) {
1383 case cmStateEnums::SHARED_LIBRARY:
1384 case cmStateEnums::MODULE_LIBRARY:
1385 configType = "DynamicLibrary";
1387 case cmStateEnums::OBJECT_LIBRARY:
1388 case cmStateEnums::STATIC_LIBRARY:
1389 configType = "StaticLibrary";
1391 case cmStateEnums::EXECUTABLE:
1392 if (this->NsightTegra &&
1393 !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
1394 // Android executables are .so too.
1395 configType = "DynamicLibrary";
1396 } else if (this->Android) {
1397 configType = "DynamicLibrary";
1399 configType = "Application";
1402 case cmStateEnums::UTILITY:
1403 case cmStateEnums::INTERFACE_LIBRARY:
1404 case cmStateEnums::GLOBAL_TARGET:
1405 if (this->NsightTegra) {
1406 // Tegra-Android platform does not understand "Utility".
1407 configType = "StaticLibrary";
1409 configType = "Utility";
1412 case cmStateEnums::UNKNOWN_LIBRARY:
1416 e1.Element("ConfigurationType", configType);
1419 if (this->MSTools) {
1420 if (!this->Managed) {
1421 this->WriteMSToolConfigurationValues(e1, c);
1423 this->WriteMSToolConfigurationValuesManaged(e1, c);
1425 } else if (this->NsightTegra) {
1426 this->WriteNsightTegraConfigurationValues(e1, c);
1427 } else if (this->Android) {
1428 this->WriteAndroidConfigurationValues(e1, c);
1433 void cmVisualStudio10TargetGenerator::WriteCEDebugProjectConfigurationValues(
1436 if (!this->GlobalGenerator->TargetsWindowsCE()) {
1439 cmValue additionalFiles =
1440 this->GeneratorTarget->GetProperty("DEPLOYMENT_ADDITIONAL_FILES");
1441 cmValue remoteDirectory =
1442 this->GeneratorTarget->GetProperty("DEPLOYMENT_REMOTE_DIRECTORY");
1443 if (!(additionalFiles || remoteDirectory)) {
1446 for (std::string const& c : this->Configurations) {
1447 Elem e1(e0, "PropertyGroup");
1448 e1.Attribute("Condition", this->CalcCondition(c));
1450 if (remoteDirectory) {
1451 e1.Element("RemoteDirectory", *remoteDirectory);
1453 if (additionalFiles) {
1454 e1.Element("CEAdditionalFiles", *additionalFiles);
1459 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
1460 Elem& e1, std::string const& config)
1462 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1463 cmValue mfcFlag = this->Makefile->GetDefinition("CMAKE_MFC_FLAG");
1465 std::string const mfcFlagValue =
1466 cmGeneratorExpression::Evaluate(*mfcFlag, this->LocalGenerator, config);
1468 std::string useOfMfcValue = "false";
1469 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
1470 if (mfcFlagValue == "1") {
1471 useOfMfcValue = "Static";
1472 } else if (mfcFlagValue == "2") {
1473 useOfMfcValue = "Dynamic";
1476 e1.Element("UseOfMfc", useOfMfcValue);
1479 if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
1480 this->ClOptions[config]->UsingUnicode()) ||
1481 this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
1482 this->GlobalGenerator->TargetsWindowsPhone() ||
1483 this->GlobalGenerator->TargetsWindowsStore() ||
1484 this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
1485 e1.Element("CharacterSet", "Unicode");
1486 } else if (this->GeneratorTarget->GetType() <=
1487 cmStateEnums::OBJECT_LIBRARY &&
1488 this->ClOptions[config]->UsingSBCS()) {
1489 e1.Element("CharacterSet", "NotSet");
1491 e1.Element("CharacterSet", "MultiByte");
1493 if (cmValue projectToolsetOverride =
1494 this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1495 e1.Element("PlatformToolset", *projectToolsetOverride);
1496 } else if (const char* toolset = gg->GetPlatformToolset()) {
1497 e1.Element("PlatformToolset", toolset);
1499 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
1500 this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
1501 e1.Element("WindowsAppContainer", "true");
1503 if (this->IPOEnabledConfigurations.count(config) > 0) {
1504 e1.Element("WholeProgramOptimization", "true");
1506 if (this->ASanEnabledConfigurations.find(config) !=
1507 this->ASanEnabledConfigurations.end()) {
1508 e1.Element("EnableAsan", "true");
1511 auto s = this->SpectreMitigation.find(config);
1512 if (s != this->SpectreMitigation.end()) {
1513 e1.Element("SpectreMitigation", s->second);
1518 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
1519 Elem& e1, std::string const& config)
1521 if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
1525 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1527 Options& o = *(this->ClOptions[config]);
1530 e1.Element("DebugSymbols", "true");
1531 e1.Element("DefineDebug", "true");
1534 std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
1535 ConvertToWindowsSlash(outDir);
1536 e1.Element("OutputPath", outDir);
1538 if (o.HasFlag("Platform")) {
1539 e1.Element("PlatformTarget", o.GetFlag("Platform"));
1540 o.RemoveFlag("Platform");
1543 if (cmValue projectToolsetOverride =
1544 this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1545 e1.Element("PlatformToolset", *projectToolsetOverride);
1546 } else if (const char* toolset = gg->GetPlatformToolset()) {
1547 e1.Element("PlatformToolset", toolset);
1550 std::string postfixName =
1551 cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
1552 std::string assemblyName = this->GeneratorTarget->GetOutputName(
1553 config, cmStateEnums::RuntimeBinaryArtifact);
1554 if (cmValue postfix = this->GeneratorTarget->GetProperty(postfixName)) {
1555 assemblyName += *postfix;
1557 e1.Element("AssemblyName", assemblyName);
1559 if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
1560 e1.Element("StartAction", "Program");
1561 e1.Element("StartProgram", outDir + assemblyName + ".exe");
1564 OptionsHelper oh(o, e1);
1568 //----------------------------------------------------------------------------
1569 void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
1570 Elem& e1, std::string const&)
1572 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1573 const char* toolset = gg->GetPlatformToolset();
1574 e1.Element("NdkToolchainVersion", toolset ? toolset : "Default");
1575 if (cmValue minApi = this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) {
1576 e1.Element("AndroidMinAPI", "android-" + *minApi);
1578 if (cmValue api = this->GeneratorTarget->GetProperty("ANDROID_API")) {
1579 e1.Element("AndroidTargetAPI", "android-" + *api);
1582 if (cmValue cpuArch = this->GeneratorTarget->GetProperty("ANDROID_ARCH")) {
1583 e1.Element("AndroidArch", *cpuArch);
1586 if (cmValue stlType =
1587 this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
1588 e1.Element("AndroidStlType", *stlType);
1592 void cmVisualStudio10TargetGenerator::WriteAndroidConfigurationValues(
1593 Elem& e1, std::string const&)
1595 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1596 if (cmValue projectToolsetOverride =
1597 this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1598 e1.Element("PlatformToolset", *projectToolsetOverride);
1599 } else if (const char* toolset = gg->GetPlatformToolset()) {
1600 e1.Element("PlatformToolset", toolset);
1602 if (cmValue stlType =
1603 this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
1604 if (*stlType != "none") {
1605 e1.Element("UseOfStl", *stlType);
1608 std::string const& apiLevel = gg->GetSystemVersion();
1609 if (!apiLevel.empty()) {
1610 e1.Element("AndroidAPILevel", cmStrCat("android-", apiLevel));
1614 void cmVisualStudio10TargetGenerator::WriteCustomCommands(Elem& e0)
1616 this->CSharpCustomCommandNames.clear();
1618 cmSourceFile const* srcCMakeLists =
1619 this->LocalGenerator->CreateVCProjBuildRule();
1621 for (cmGeneratorTarget::AllConfigSource const& si :
1622 this->GeneratorTarget->GetAllConfigSources()) {
1623 if (si.Source == srcCMakeLists) {
1624 // Skip explicit reference to CMakeLists.txt source.
1627 this->WriteCustomCommand(e0, si.Source);
1630 // Add CMakeLists.txt file with rule to re-run CMake for user convenience.
1631 if (this->GeneratorTarget->GetType() != cmStateEnums::GLOBAL_TARGET &&
1632 this->GeneratorTarget->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
1633 if (srcCMakeLists) {
1634 // Write directly rather than through WriteCustomCommand because
1635 // we do not want the de-duplication and it has no dependencies.
1636 if (cmCustomCommand const* command = srcCMakeLists->GetCustomCommand()) {
1637 this->WriteCustomRule(e0, srcCMakeLists, *command);
1643 void cmVisualStudio10TargetGenerator::WriteCustomCommand(
1644 Elem& e0, cmSourceFile const* sf)
1646 if (this->LocalGenerator->GetSourcesVisited(this->GeneratorTarget)
1649 if (std::vector<cmSourceFile*> const* depends =
1650 this->GeneratorTarget->GetSourceDepends(sf)) {
1651 for (cmSourceFile const* di : *depends) {
1652 this->WriteCustomCommand(e0, di);
1655 if (cmCustomCommand const* command = sf->GetCustomCommand()) {
1656 // C# projects write their <Target> within WriteCustomRule()
1657 this->WriteCustomRule(e0, sf, *command);
1662 void cmVisualStudio10TargetGenerator::WriteCustomRule(
1663 Elem& e0, cmSourceFile const* source, cmCustomCommand const& command)
1665 std::string sourcePath = source->GetFullPath();
1666 // VS 10 will always rebuild a custom command attached to a .rule
1667 // file that doesn't exist so create the file explicitly.
1668 if (source->GetPropertyAsBool("__CMAKE_RULE")) {
1669 if (!cmSystemTools::FileExists(sourcePath)) {
1670 // Make sure the path exists for the file
1671 std::string path = cmSystemTools::GetFilenamePath(sourcePath);
1672 cmSystemTools::MakeDirectory(path);
1673 cmsys::ofstream fout(sourcePath.c_str());
1675 fout << "# generated from CMake\n";
1678 // Force given file to have a very old timestamp, thus
1679 // preventing dependent rebuilds.
1680 this->ForceOld(sourcePath);
1683 cmStrCat("Could not create file: [", sourcePath, "] ");
1684 cmSystemTools::Error(error + cmSystemTools::GetLastSystemError());
1688 cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
1690 std::unique_ptr<Elem> spe1;
1691 std::unique_ptr<Elem> spe2;
1692 if (this->ProjectType != VsProjectType::csproj) {
1693 spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
1694 spe2 = cm::make_unique<Elem>(*spe1, "CustomBuild");
1695 this->WriteSource(*spe2, source);
1696 spe2->SetHasElements();
1697 if (command.GetStdPipesUTF8()) {
1698 this->WriteStdOutEncodingUtf8(*spe2);
1701 Elem e1(e0, "ItemGroup");
1702 Elem e2(e1, "None");
1703 this->WriteSource(e2, source);
1704 e2.SetHasElements();
1706 for (std::string const& c : this->Configurations) {
1707 cmCustomCommandGenerator ccg(command, c, lg, true);
1708 std::string comment = lg->ConstructComment(ccg);
1709 comment = cmVS10EscapeComment(comment);
1710 std::string script = lg->ConstructScript(ccg);
1711 bool symbolic = false;
1712 // input files for custom command
1713 std::stringstream additional_inputs;
1715 const char* sep = "";
1716 if (this->ProjectType == VsProjectType::csproj) {
1717 // csproj files do not attach the command to a specific file
1718 // so the primary input must be listed explicitly.
1719 additional_inputs << source->GetFullPath();
1723 // Avoid listing an input more than once.
1724 std::set<std::string> unique_inputs;
1725 // The source is either implicit an input or has been added above.
1726 unique_inputs.insert(source->GetFullPath());
1728 for (std::string const& d : ccg.GetDepends()) {
1730 if (lg->GetRealDependency(d, c, dep)) {
1731 if (!unique_inputs.insert(dep).second) {
1735 ConvertToWindowsSlash(dep);
1736 additional_inputs << sep << dep;
1739 if (cmSourceFile* sf = this->Makefile->GetSource(
1740 dep, cmSourceFileLocationKind::Known)) {
1741 symbolic = sf->GetPropertyAsBool("SYMBOLIC");
1746 if (this->ProjectType != VsProjectType::csproj) {
1747 additional_inputs << sep << "%(AdditionalInputs)";
1750 // output files for custom command
1751 std::stringstream outputs;
1753 const char* sep = "";
1754 for (std::string const& o : ccg.GetOutputs()) {
1755 std::string out = o;
1756 ConvertToWindowsSlash(out);
1757 outputs << sep << out;
1760 if (cmSourceFile* sf = this->Makefile->GetSource(
1761 o, cmSourceFileLocationKind::Known)) {
1762 symbolic = sf->GetPropertyAsBool("SYMBOLIC");
1767 script += lg->FinishConstructScript(this->ProjectType);
1768 if (this->ProjectType == VsProjectType::csproj) {
1769 std::string name = "CustomCommand_" + c + "_" +
1770 cmSystemTools::ComputeStringMD5(sourcePath);
1771 this->WriteCustomRuleCSharp(e0, c, name, script, additional_inputs.str(),
1772 outputs.str(), comment, ccg);
1774 this->WriteCustomRuleCpp(*spe2, c, script, additional_inputs.str(),
1775 outputs.str(), comment, ccg, symbolic);
1780 void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
1781 Elem& e2, std::string const& config, std::string const& script,
1782 std::string const& additional_inputs, std::string const& outputs,
1783 std::string const& comment, cmCustomCommandGenerator const& ccg,
1786 const std::string cond = this->CalcCondition(config);
1787 e2.WritePlatformConfigTag("Message", cond, comment);
1788 e2.WritePlatformConfigTag("Command", cond, script);
1789 e2.WritePlatformConfigTag("AdditionalInputs", cond, additional_inputs);
1790 e2.WritePlatformConfigTag("Outputs", cond, outputs);
1791 if (this->LocalGenerator->GetVersion() >
1792 cmGlobalVisualStudioGenerator::VSVersion::VS10) {
1793 // VS >= 11 let us turn off linking of custom command outputs.
1794 e2.WritePlatformConfigTag("LinkObjects", cond, "false");
1797 this->LocalGenerator->GetVersion() >=
1798 cmGlobalVisualStudioGenerator::VSVersion::VS16) {
1799 // VS >= 16.4 warn if outputs are not created, but one of our
1800 // outputs is marked SYMBOLIC and not expected to be created.
1801 e2.WritePlatformConfigTag("VerifyInputsAndOutputsExist", cond, "false");
1804 std::string depfile = ccg.GetFullDepfile();
1805 if (!depfile.empty()) {
1806 this->HaveCustomCommandDepfile = true;
1807 std::string internal_depfile = ccg.GetInternalDepfile();
1808 ConvertToWindowsSlash(internal_depfile);
1809 e2.WritePlatformConfigTag("DepFileAdditionalInputsFile", cond,
1814 void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
1815 Elem& e0, std::string const& config, std::string const& name,
1816 std::string const& script, std::string const& inputs,
1817 std::string const& outputs, std::string const& comment,
1818 cmCustomCommandGenerator const& ccg)
1820 if (!ccg.GetFullDepfile().empty()) {
1821 this->Makefile->IssueMessage(
1822 MessageType::FATAL_ERROR,
1823 cmStrCat("CSharp target \"", this->GeneratorTarget->GetName(),
1824 "\" does not support add_custom_command DEPFILE."));
1826 this->CSharpCustomCommandNames.insert(name);
1827 Elem e1(e0, "Target");
1828 e1.Attribute("Condition", this->CalcCondition(config));
1829 e1.S << "\n Name=\"" << name << "\"";
1830 e1.S << "\n Inputs=\"" << cmVS10EscapeAttr(inputs) << "\"";
1831 e1.S << "\n Outputs=\"" << cmVS10EscapeAttr(outputs) << "\"";
1832 if (!comment.empty()) {
1833 Elem(e1, "Exec").Attribute("Command", "echo " + comment);
1835 Elem(e1, "Exec").Attribute("Command", script);
1838 std::string cmVisualStudio10TargetGenerator::ConvertPath(
1839 std::string const& path, bool forceRelative)
1841 return forceRelative
1842 ? cmSystemTools::RelativePath(
1843 this->LocalGenerator->GetCurrentBinaryDirectory(), path)
1847 static void ConvertToWindowsSlash(std::string& s)
1849 // first convert all of the slashes
1850 for (auto& ch : s) {
1857 void cmVisualStudio10TargetGenerator::WriteGroups()
1859 if (this->ProjectType == VsProjectType::csproj) {
1863 // collect up group information
1864 std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
1866 std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
1867 this->GeneratorTarget->GetAllConfigSources();
1869 std::set<cmSourceGroup const*> groupsUsed;
1870 for (cmGeneratorTarget::AllConfigSource const& si : sources) {
1871 std::string const& source = si.Source->GetFullPath();
1872 cmSourceGroup* sourceGroup =
1873 this->Makefile->FindSourceGroup(source, sourceGroups);
1874 groupsUsed.insert(sourceGroup);
1877 if (cmSourceFile const* srcCMakeLists =
1878 this->LocalGenerator->CreateVCProjBuildRule()) {
1879 std::string const& source = srcCMakeLists->GetFullPath();
1880 cmSourceGroup* sourceGroup =
1881 this->Makefile->FindSourceGroup(source, sourceGroups);
1882 groupsUsed.insert(sourceGroup);
1885 this->AddMissingSourceGroups(groupsUsed, sourceGroups);
1887 // Write out group file
1888 std::string path = cmStrCat(
1889 this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->Name,
1890 computeProjectFileExtension(this->GeneratorTarget), ".filters");
1891 cmGeneratedFileStream fout(path);
1892 fout.SetCopyIfDifferent(true);
1893 char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
1894 fout.write(magic, 3);
1896 fout << "<?xml version=\"1.0\" encoding=\""
1897 << this->GlobalGenerator->Encoding() << "\"?>";
1899 Elem e0(fout, "Project");
1900 e0.Attribute("ToolsVersion", this->GlobalGenerator->GetToolsVersion());
1901 e0.Attribute("xmlns",
1902 "http://schemas.microsoft.com/developer/msbuild/2003");
1904 for (auto const& ti : this->Tools) {
1905 this->WriteGroupSources(e0, ti.first, ti.second, sourceGroups);
1908 // Added files are images and the manifest.
1909 if (!this->AddedFiles.empty()) {
1910 Elem e1(e0, "ItemGroup");
1911 e1.SetHasElements();
1912 for (std::string const& oi : this->AddedFiles) {
1913 std::string fileName =
1914 cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(oi));
1915 if (fileName == "wmappmanifest.xml") {
1917 e2.Attribute("Include", oi);
1918 e2.Element("Filter", "Resource Files");
1919 } else if (cmSystemTools::GetFilenameExtension(fileName) ==
1921 Elem e2(e1, "AppxManifest");
1922 e2.Attribute("Include", oi);
1923 e2.Element("Filter", "Resource Files");
1924 } else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx") {
1925 Elem e2(e1, "None");
1926 e2.Attribute("Include", oi);
1927 e2.Element("Filter", "Resource Files");
1929 Elem e2(e1, "Image");
1930 e2.Attribute("Include", oi);
1931 e2.Element("Filter", "Resource Files");
1936 if (!this->ResxObjs.empty()) {
1937 Elem e1(e0, "ItemGroup");
1938 for (cmSourceFile const* oi : this->ResxObjs) {
1939 std::string obj = oi->GetFullPath();
1940 ConvertToWindowsSlash(obj);
1941 Elem e2(e1, "EmbeddedResource");
1942 e2.Attribute("Include", obj);
1943 e2.Element("Filter", "Resource Files");
1947 Elem e1(e0, "ItemGroup");
1948 e1.SetHasElements();
1949 std::vector<cmSourceGroup const*> groupsVec(groupsUsed.begin(),
1951 std::sort(groupsVec.begin(), groupsVec.end(),
1952 [](cmSourceGroup const* l, cmSourceGroup const* r) {
1953 return l->GetFullName() < r->GetFullName();
1955 for (cmSourceGroup const* sg : groupsVec) {
1956 std::string const& name = sg->GetFullName();
1957 if (!name.empty()) {
1958 std::string guidName = "SG_Filter_" + name;
1959 std::string guid = this->GlobalGenerator->GetGUID(guidName);
1960 Elem e2(e1, "Filter");
1961 e2.Attribute("Include", name);
1962 e2.Element("UniqueIdentifier", "{" + guid + "}");
1966 if (!this->ResxObjs.empty() || !this->AddedFiles.empty()) {
1967 std::string guidName = "SG_Filter_Resource Files";
1968 std::string guid = this->GlobalGenerator->GetGUID(guidName);
1969 Elem e2(e1, "Filter");
1970 e2.Attribute("Include", "Resource Files");
1971 e2.Element("UniqueIdentifier", "{" + guid + "}");
1972 e2.Element("Extensions",
1973 "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;"
1974 "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms");
1981 this->GlobalGenerator->FileReplacedDuringGenerate(path);
1985 // Add to groupsUsed empty source groups that have non-empty children.
1986 void cmVisualStudio10TargetGenerator::AddMissingSourceGroups(
1987 std::set<cmSourceGroup const*>& groupsUsed,
1988 const std::vector<cmSourceGroup>& allGroups)
1990 for (cmSourceGroup const& current : allGroups) {
1991 std::vector<cmSourceGroup> const& children = current.GetGroupChildren();
1992 if (children.empty()) {
1993 continue; // the group is really empty
1996 this->AddMissingSourceGroups(groupsUsed, children);
1998 if (groupsUsed.count(¤t) > 0) {
1999 continue; // group has already been added to set
2002 // check if it least one of the group's descendants is not empty
2003 // (at least one child must already have been added)
2004 auto child_it = children.begin();
2005 while (child_it != children.end()) {
2006 if (groupsUsed.count(&(*child_it)) > 0) {
2007 break; // found a child that was already added => add current group too
2012 if (child_it == children.end()) {
2013 continue; // no descendants have source files => ignore this group
2016 groupsUsed.insert(¤t);
2020 void cmVisualStudio10TargetGenerator::WriteGroupSources(
2021 Elem& e0, std::string const& name, ToolSources const& sources,
2022 std::vector<cmSourceGroup>& sourceGroups)
2024 Elem e1(e0, "ItemGroup");
2025 e1.SetHasElements();
2026 for (ToolSource const& s : sources) {
2027 cmSourceFile const* sf = s.SourceFile;
2028 std::string const& source = sf->GetFullPath();
2029 cmSourceGroup* sourceGroup =
2030 this->Makefile->FindSourceGroup(source, sourceGroups);
2031 std::string const& filter = sourceGroup->GetFullName();
2032 std::string path = this->ConvertPath(source, s.RelativePath);
2033 ConvertToWindowsSlash(path);
2035 e2.Attribute("Include", path);
2036 if (!filter.empty()) {
2037 e2.Element("Filter", filter);
2042 void cmVisualStudio10TargetGenerator::WriteHeaderSource(
2043 Elem& e1, cmSourceFile const* sf, ConfigToSettings const& toolSettings)
2045 std::string const& fileName = sf->GetFullPath();
2046 Elem e2(e1, "ClInclude");
2047 this->WriteSource(e2, sf);
2048 if (this->IsResxHeader(fileName)) {
2049 e2.Element("FileType", "CppForm");
2050 } else if (this->IsXamlHeader(fileName)) {
2051 e2.Element("DependentUpon",
2052 fileName.substr(0, fileName.find_last_of(".")));
2054 this->FinishWritingSource(e2, toolSettings);
2057 void cmVisualStudio10TargetGenerator::ParseSettingsProperty(
2058 const std::string& settingsPropertyValue, ConfigToSettings& toolSettings)
2060 if (!settingsPropertyValue.empty()) {
2061 cmGeneratorExpression ge;
2063 std::unique_ptr<cmCompiledGeneratorExpression> cge =
2064 ge.Parse(settingsPropertyValue);
2066 for (const std::string& config : this->Configurations) {
2067 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2069 std::vector<std::string> settings = cmExpandedList(evaluated);
2070 for (const std::string& setting : settings) {
2071 const std::string::size_type assignment = setting.find('=');
2072 if (assignment != std::string::npos) {
2073 const std::string propName = setting.substr(0, assignment);
2074 const std::string propValue = setting.substr(assignment + 1);
2076 if (!propValue.empty()) {
2077 toolSettings[config][propName] = propValue;
2085 bool cmVisualStudio10TargetGenerator::PropertyIsSameInAllConfigs(
2086 const ConfigToSettings& toolSettings, const std::string& propName)
2088 std::string firstPropValue = "";
2089 for (const auto& configToSettings : toolSettings) {
2090 const std::unordered_map<std::string, std::string>& settings =
2091 configToSettings.second;
2093 if (firstPropValue.empty()) {
2094 if (settings.find(propName) != settings.end()) {
2095 firstPropValue = settings.find(propName)->second;
2099 if (settings.find(propName) == settings.end()) {
2103 if (settings.find(propName)->second != firstPropValue) {
2111 void cmVisualStudio10TargetGenerator::WriteExtraSource(
2112 Elem& e1, cmSourceFile const* sf, ConfigToSettings& toolSettings)
2114 bool toolHasSettings = false;
2115 const char* tool = "None";
2116 std::string settingsGenerator;
2117 std::string settingsLastGenOutput;
2118 std::string sourceLink;
2119 std::string subType;
2120 std::string copyToOutDir;
2121 std::string includeInVsix;
2122 std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
2124 if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
2125 toolHasSettings = true;
2127 if (ext == "hlsl") {
2129 // Figure out the type of shader compiler to use.
2130 if (cmValue st = sf->GetProperty("VS_SHADER_TYPE")) {
2131 for (const std::string& config : this->Configurations) {
2132 toolSettings[config]["ShaderType"] = *st;
2135 // Figure out which entry point to use if any
2136 if (cmValue se = sf->GetProperty("VS_SHADER_ENTRYPOINT")) {
2137 for (const std::string& config : this->Configurations) {
2138 toolSettings[config]["EntryPointName"] = *se;
2141 // Figure out which shader model to use if any
2142 if (cmValue sm = sf->GetProperty("VS_SHADER_MODEL")) {
2143 for (const std::string& config : this->Configurations) {
2144 toolSettings[config]["ShaderModel"] = *sm;
2147 // Figure out which output header file to use if any
2148 if (cmValue ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
2149 for (const std::string& config : this->Configurations) {
2150 toolSettings[config]["HeaderFileOutput"] = *ohf;
2153 // Figure out which variable name to use if any
2154 if (cmValue vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
2155 for (const std::string& config : this->Configurations) {
2156 toolSettings[config]["VariableName"] = *vn;
2159 // Figure out if there's any additional flags to use
2160 if (cmValue saf = sf->GetProperty("VS_SHADER_FLAGS")) {
2161 cmGeneratorExpression ge;
2162 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*saf);
2164 for (const std::string& config : this->Configurations) {
2165 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2167 if (!evaluated.empty()) {
2168 toolSettings[config]["AdditionalOptions"] = evaluated;
2172 // Figure out if debug information should be generated
2173 if (cmValue sed = sf->GetProperty("VS_SHADER_ENABLE_DEBUG")) {
2174 cmGeneratorExpression ge;
2175 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sed);
2177 for (const std::string& config : this->Configurations) {
2178 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2180 if (!evaluated.empty()) {
2181 toolSettings[config]["EnableDebuggingInformation"] =
2182 cmIsOn(evaluated) ? "true" : "false";
2186 // Figure out if optimizations should be disabled
2187 if (cmValue sdo = sf->GetProperty("VS_SHADER_DISABLE_OPTIMIZATIONS")) {
2188 cmGeneratorExpression ge;
2189 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sdo);
2191 for (const std::string& config : this->Configurations) {
2192 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2194 if (!evaluated.empty()) {
2195 toolSettings[config]["DisableOptimizations"] =
2196 cmIsOn(evaluated) ? "true" : "false";
2200 if (cmValue sofn = sf->GetProperty("VS_SHADER_OBJECT_FILE_NAME")) {
2201 for (const std::string& config : this->Configurations) {
2202 toolSettings[config]["ObjectFileOutput"] = *sofn;
2205 } else if (ext == "jpg" || ext == "png") {
2207 } else if (ext == "resw") {
2208 tool = "PRIResource";
2209 } else if (ext == "xml") {
2211 } else if (ext == "natvis") {
2213 } else if (ext == "settings") {
2214 settingsLastGenOutput =
2215 cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
2216 std::size_t pos = settingsLastGenOutput.find(".settings");
2217 settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
2218 settingsGenerator = "SettingsSingleFileGenerator";
2219 toolHasSettings = true;
2220 } else if (ext == "vsixmanifest") {
2221 subType = "Designer";
2223 if (cmValue c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
2226 toolHasSettings = true;
2228 if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
2229 includeInVsix = "True";
2231 toolHasSettings = true;
2234 // Collect VS_CSHARP_* property values (if some are set)
2235 std::map<std::string, std::string> sourceFileTags;
2236 this->GetCSharpSourceProperties(sf, sourceFileTags);
2238 if (this->NsightTegra) {
2239 // Nsight Tegra needs specific file types to check up-to-dateness.
2240 std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
2241 if (name == "androidmanifest.xml" || name == "build.xml" ||
2242 name == "proguard.cfg" || name == "proguard-project.txt" ||
2243 ext == "properties") {
2244 tool = "AndroidBuild";
2245 } else if (ext == "java") {
2247 } else if (ext == "asm" || ext == "s") {
2252 cmValue toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
2253 if (cmNonempty(toolOverride)) {
2254 tool = toolOverride->c_str();
2257 std::string deployContent;
2258 std::string deployLocation;
2259 if (this->GlobalGenerator->TargetsWindowsPhone() ||
2260 this->GlobalGenerator->TargetsWindowsStore()) {
2261 cmValue content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
2262 if (cmNonempty(content)) {
2263 toolHasSettings = true;
2264 deployContent = *content;
2266 cmValue location = sf->GetProperty("VS_DEPLOYMENT_LOCATION");
2267 if (cmNonempty(location)) {
2268 deployLocation = *location;
2273 if (ParsedToolTargetSettings.find(tool) == ParsedToolTargetSettings.end()) {
2274 cmValue toolTargetProperty = this->GeneratorTarget->Target->GetProperty(
2275 "VS_SOURCE_SETTINGS_" + std::string(tool));
2276 ConfigToSettings toolTargetSettings;
2277 if (toolTargetProperty) {
2278 ParseSettingsProperty(*toolTargetProperty, toolTargetSettings);
2281 ParsedToolTargetSettings[tool] = toolTargetSettings;
2284 for (const auto& configToSetting : ParsedToolTargetSettings[tool]) {
2285 for (const auto& setting : configToSetting.second) {
2286 toolSettings[configToSetting.first][setting.first] = setting.second;
2290 if (!toolSettings.empty()) {
2291 toolHasSettings = true;
2295 this->WriteSource(e2, sf);
2296 if (toolHasSettings) {
2297 e2.SetHasElements();
2299 this->FinishWritingSource(e2, toolSettings);
2301 if (!deployContent.empty()) {
2302 cmGeneratorExpression ge;
2303 std::unique_ptr<cmCompiledGeneratorExpression> cge =
2304 ge.Parse(deployContent);
2305 // Deployment location cannot be set on a configuration basis
2306 if (!deployLocation.empty()) {
2307 e2.Element("Link", deployLocation + "\\%(FileName)%(Extension)");
2309 for (size_t i = 0; i != this->Configurations.size(); ++i) {
2310 if (cge->Evaluate(this->LocalGenerator, this->Configurations[i]) ==
2312 e2.WritePlatformConfigTag("DeploymentContent",
2313 "'$(Configuration)|$(Platform)'=='" +
2314 this->Configurations[i] + "|" +
2315 this->Platform + "'",
2318 e2.WritePlatformConfigTag("ExcludedFromBuild",
2319 "'$(Configuration)|$(Platform)'=='" +
2320 this->Configurations[i] + "|" +
2321 this->Platform + "'",
2327 if (!settingsGenerator.empty()) {
2328 e2.Element("Generator", settingsGenerator);
2330 if (!settingsLastGenOutput.empty()) {
2331 e2.Element("LastGenOutput", settingsLastGenOutput);
2333 if (!subType.empty()) {
2334 e2.Element("SubType", subType);
2336 if (!copyToOutDir.empty()) {
2337 e2.Element("CopyToOutputDirectory", copyToOutDir);
2339 if (!includeInVsix.empty()) {
2340 e2.Element("IncludeInVSIX", includeInVsix);
2342 // write source file specific tags
2343 this->WriteCSharpSourceProperties(e2, sourceFileTags);
2347 void cmVisualStudio10TargetGenerator::WriteSource(Elem& e2,
2348 cmSourceFile const* sf)
2350 // Visual Studio tools append relative paths to the current dir, as in:
2352 // c:\path\to\current\dir\..\..\..\relative\path\to\source.c
2354 // and fail if this exceeds the maximum allowed path length. Our path
2355 // conversion uses full paths when possible to allow deeper trees.
2356 // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
2357 // we must use relative paths.
2358 bool forceRelative = sf->GetLanguage() == "CUDA";
2359 std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative);
2360 if (this->LocalGenerator->GetVersion() ==
2361 cmGlobalVisualStudioGenerator::VSVersion::VS10 &&
2362 cmSystemTools::FileIsFullPath(sourceFile)) {
2363 // Normal path conversion resulted in a full path. VS 10 (but not 11)
2364 // refuses to show the property page in the IDE for a source file with a
2365 // full path (not starting in a '.' or '/' AFAICT). CMake <= 2.8.4 used a
2366 // relative path but to allow deeper build trees CMake 2.8.[5678] used a
2367 // full path except for custom commands. Custom commands do not work
2368 // without a relative path, but they do not seem to be involved in tools
2369 // with the above behavior. For other sources we now use a relative path
2370 // when the combined path will not be too long so property pages appear.
2371 std::string sourceRel = this->ConvertPath(sf->GetFullPath(), true);
2372 size_t const maxLen = 250;
2373 if (sf->GetCustomCommand() ||
2374 ((this->LocalGenerator->GetCurrentBinaryDirectory().length() + 1 +
2375 sourceRel.length()) <= maxLen)) {
2376 forceRelative = true;
2377 sourceFile = sourceRel;
2379 this->GlobalGenerator->PathTooLong(this->GeneratorTarget, sf, sourceRel);
2382 ConvertToWindowsSlash(sourceFile);
2383 e2.Attribute("Include", sourceFile);
2385 if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
2386 // For out of source projects we have to provide a link (if not specified
2387 // via property) for every source file (besides .cs files) otherwise they
2388 // will not be visible in VS at all.
2389 // First we check if the file is in a source group, then we check if the
2390 // file path is relative to current source- or binary-dir, otherwise it is
2391 // added with the plain filename without any path. This means the file will
2392 // show up at root-level of the csproj (where CMakeLists.txt etc. are).
2393 std::string link = this->GetCSharpSourceLink(sf);
2395 link = cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
2396 e2.Element("Link", link);
2399 ToolSource toolSource = { sf, forceRelative };
2400 this->Tools[e2.Tag].push_back(toolSource);
2403 void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
2405 if (this->GeneratorTarget->GetType() == cmStateEnums::GLOBAL_TARGET) {
2409 const bool haveUnityBuild =
2410 this->GeneratorTarget->GetPropertyAsBool("UNITY_BUILD");
2412 if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
2413 Elem e1(e0, "PropertyGroup");
2414 e1.Element("EnableUnitySupport", "true");
2417 Elem e1(e0, "ItemGroup");
2418 e1.SetHasElements();
2420 std::vector<size_t> all_configs;
2421 for (size_t ci = 0; ci < this->Configurations.size(); ++ci) {
2422 all_configs.push_back(ci);
2425 std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
2426 this->GeneratorTarget->GetAllConfigSources();
2428 cmSourceFile const* srcCMakeLists =
2429 this->LocalGenerator->CreateVCProjBuildRule();
2431 for (cmGeneratorTarget::AllConfigSource const& si : sources) {
2432 if (si.Source == srcCMakeLists) {
2433 // Skip explicit reference to CMakeLists.txt source.
2437 ConfigToSettings toolSettings;
2438 for (const auto& config : this->Configurations) {
2439 toolSettings[config];
2441 if (cmValue p = si.Source->GetProperty("VS_SETTINGS")) {
2442 ParseSettingsProperty(*p, toolSettings);
2445 const char* tool = nullptr;
2447 case cmGeneratorTarget::SourceKindAppManifest:
2448 tool = "AppxManifest";
2450 case cmGeneratorTarget::SourceKindCertificate:
2453 case cmGeneratorTarget::SourceKindCustomCommand:
2454 // Handled elsewhere.
2456 case cmGeneratorTarget::SourceKindExternalObject:
2458 if (this->LocalGenerator->GetVersion() <
2459 cmGlobalVisualStudioGenerator::VSVersion::VS11) {
2460 // For VS == 10 we cannot use LinkObjects to avoid linking custom
2461 // command outputs. If an object file is generated in this target,
2462 // then vs10 will use it in the build, and we have to list it as
2463 // None instead of Object.
2464 std::vector<cmSourceFile*> const* d =
2465 this->GeneratorTarget->GetSourceDepends(si.Source);
2466 if (d && !d->empty()) {
2471 case cmGeneratorTarget::SourceKindExtra:
2472 this->WriteExtraSource(e1, si.Source, toolSettings);
2474 case cmGeneratorTarget::SourceKindHeader:
2475 this->WriteHeaderSource(e1, si.Source, toolSettings);
2477 case cmGeneratorTarget::SourceKindIDL:
2480 case cmGeneratorTarget::SourceKindManifest:
2481 // Handled elsewhere.
2483 case cmGeneratorTarget::SourceKindModuleDefinition:
2486 case cmGeneratorTarget::SourceKindUnityBatched:
2487 case cmGeneratorTarget::SourceKindObjectSource: {
2488 const std::string& lang = si.Source->GetLanguage();
2489 if (lang == "C" || lang == "CXX") {
2491 } else if (lang == "ASM_MASM" &&
2492 this->GlobalGenerator->IsMasmEnabled()) {
2494 } else if (lang == "ASM_NASM" &&
2495 this->GlobalGenerator->IsNasmEnabled()) {
2497 } else if (lang == "RC") {
2498 tool = "ResourceCompile";
2499 } else if (lang == "CSharp") {
2501 } else if (lang == "CUDA" && this->GlobalGenerator->IsCudaEnabled()) {
2502 tool = "CudaCompile";
2507 case cmGeneratorTarget::SourceKindResx:
2508 this->ResxObjs.push_back(si.Source);
2510 case cmGeneratorTarget::SourceKindXaml:
2511 this->XamlObjs.push_back(si.Source);
2516 // Compute set of configurations to exclude, if any.
2517 std::vector<size_t> const& include_configs = si.Configs;
2518 std::vector<size_t> exclude_configs;
2519 std::set_difference(all_configs.begin(), all_configs.end(),
2520 include_configs.begin(), include_configs.end(),
2521 std::back_inserter(exclude_configs));
2524 bool isCSharp = (si.Source->GetLanguage() == "CSharp");
2525 if (isCSharp && exclude_configs.size() > 0) {
2526 std::stringstream conditions;
2527 bool firstConditionSet{ false };
2528 for (const auto& ci : include_configs) {
2529 if (firstConditionSet) {
2530 conditions << " Or ";
2532 conditions << "('$(Configuration)|$(Platform)'=='" +
2533 this->Configurations[ci] + "|" + this->Platform + "')";
2534 firstConditionSet = true;
2536 e2.Attribute("Condition", conditions.str());
2538 this->WriteSource(e2, si.Source);
2540 bool useNativeUnityBuild = false;
2541 if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
2542 // Magic value taken from cmGlobalVisualStudioVersionedGenerator.cxx
2543 static const std::string vs15 = "141";
2544 std::string toolset =
2545 this->GlobalGenerator->GetPlatformToolsetString();
2546 cmSystemTools::ReplaceString(toolset, "v", "");
2548 if (toolset.empty() ||
2549 cmSystemTools::VersionCompareGreaterEq(toolset, vs15)) {
2550 useNativeUnityBuild = true;
2554 if (haveUnityBuild && strcmp(tool, "ClCompile") == 0 &&
2555 si.Source->GetProperty("UNITY_SOURCE_FILE")) {
2556 if (useNativeUnityBuild) {
2558 "IncludeInUnityFile",
2559 si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")
2562 e2.Attribute("CustomUnityFile", "true");
2564 std::string unityDir = cmSystemTools::GetFilenamePath(
2565 *si.Source->GetProperty("UNITY_SOURCE_FILE"));
2566 e2.Attribute("UnityFilesDirectory", unityDir);
2568 // Visual Studio versions prior to 2017 15.8 do not know about unity
2569 // builds, thus we exclude the files already part of unity sources.
2570 if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
2571 exclude_configs = all_configs;
2576 if (si.Kind == cmGeneratorTarget::SourceKindObjectSource ||
2577 si.Kind == cmGeneratorTarget::SourceKindUnityBatched) {
2578 this->OutputSourceSpecificFlags(e2, si.Source);
2580 if (si.Source->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
2581 e2.Element("PrecompiledHeader", "NotUsing");
2583 if (!isCSharp && !exclude_configs.empty()) {
2584 this->WriteExcludeFromBuild(e2, exclude_configs);
2587 this->FinishWritingSource(e2, toolSettings);
2591 if (this->IsMissingFiles) {
2592 this->WriteMissingFiles(e1);
2596 void cmVisualStudio10TargetGenerator::FinishWritingSource(
2597 Elem& e2, ConfigToSettings const& toolSettings)
2599 std::vector<std::string> writtenSettings;
2600 for (const auto& configSettings : toolSettings) {
2601 for (const auto& setting : configSettings.second) {
2603 if (std::find(writtenSettings.begin(), writtenSettings.end(),
2604 setting.first) != writtenSettings.end()) {
2608 if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
2609 e2.Element(setting.first, setting.second);
2610 writtenSettings.push_back(setting.first);
2612 e2.WritePlatformConfigTag(setting.first,
2613 "'$(Configuration)|$(Platform)'=='" +
2614 configSettings.first + "|" +
2615 this->Platform + "'",
2622 void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
2623 Elem& e2, cmSourceFile const* source)
2625 cmSourceFile const& sf = *source;
2627 std::string objectName;
2628 if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
2629 objectName = this->GeneratorTarget->GetObjectName(&sf);
2632 bool configDependentFlags = false;
2633 std::string options;
2634 bool configDependentOptions = false;
2635 std::string defines;
2636 bool configDependentDefines = false;
2637 std::string includes;
2638 bool configDependentIncludes = false;
2639 if (cmValue cflags = sf.GetProperty("COMPILE_FLAGS")) {
2640 configDependentFlags =
2641 cmGeneratorExpression::Find(*cflags) != std::string::npos;
2644 if (cmValue coptions = sf.GetProperty("COMPILE_OPTIONS")) {
2645 configDependentOptions =
2646 cmGeneratorExpression::Find(*coptions) != std::string::npos;
2647 options += *coptions;
2649 if (cmValue cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
2650 configDependentDefines =
2651 cmGeneratorExpression::Find(*cdefs) != std::string::npos;
2654 if (cmValue cincludes = sf.GetProperty("INCLUDE_DIRECTORIES")) {
2655 configDependentIncludes =
2656 cmGeneratorExpression::Find(*cincludes) != std::string::npos;
2657 includes += *cincludes;
2660 // Force language if the file extension does not match.
2661 // Note that MSVC treats the upper-case '.C' extension as C and not C++.
2662 std::string const ext = sf.GetExtension();
2663 std::string const extLang = ext == "C"
2665 : this->GlobalGenerator->GetLanguageFromExtension(ext.c_str());
2666 std::string lang = this->LocalGenerator->GetSourceFileLanguage(sf);
2667 const char* compileAs = 0;
2668 if (lang != extLang) {
2669 if (lang == "CXX") {
2670 // force a C++ file type
2671 compileAs = "CompileAsCpp";
2672 } else if (lang == "C") {
2674 compileAs = "CompileAsC";
2678 bool noWinRT = this->TargetCompileAsWinRT && lang == "C";
2679 // for the first time we need a new line if there is something
2681 if (!objectName.empty()) {
2682 if (lang == "CUDA") {
2683 e2.Element("CompileOut", "$(IntDir)/" + objectName);
2685 e2.Element("ObjectFileName", "$(IntDir)/" + objectName);
2689 if (lang == "ASM_NASM") {
2690 if (cmValue objectDeps = sf.GetProperty("OBJECT_DEPENDS")) {
2691 std::string dependencies;
2692 std::vector<std::string> depends = cmExpandedList(*objectDeps);
2693 const char* sep = "";
2694 for (std::string& d : depends) {
2695 ConvertToWindowsSlash(d);
2696 dependencies += sep;
2700 e2.Element("AdditionalDependencies", dependencies);
2704 for (std::string const& config : this->Configurations) {
2705 std::string configUpper = cmSystemTools::UpperCase(config);
2706 std::string configDefines = defines;
2707 std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
2708 if (cmValue ccdefs = sf.GetProperty(defPropName)) {
2709 if (!configDefines.empty()) {
2710 configDefines += ";";
2712 configDependentDefines |=
2713 cmGeneratorExpression::Find(*ccdefs) != std::string::npos;
2714 configDefines += *ccdefs;
2717 // We have pch state in the following situation:
2718 // 1. We have SKIP_PRECOMPILE_HEADERS == true
2719 // 2. We are creating the pre-compiled header
2720 // 3. We are a different language than the linker language AND pch is
2722 std::string const& linkLanguage =
2723 this->GeneratorTarget->GetLinkerLanguage(config);
2724 std::string const& pchSource =
2725 this->GeneratorTarget->GetPchSource(config, lang);
2726 const bool skipPCH =
2727 pchSource.empty() || sf.GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS");
2728 const bool makePCH = (sf.GetFullPath() == pchSource);
2729 const bool useSharedPCH = !skipPCH && (lang == linkLanguage);
2730 const bool useDifferentLangPCH = !skipPCH && (lang != linkLanguage);
2731 const bool useNoPCH = skipPCH && (lang != linkLanguage) &&
2732 !this->GeneratorTarget->GetPchHeader(config, linkLanguage).empty();
2733 const bool needsPCHFlags =
2734 (makePCH || useSharedPCH || useDifferentLangPCH || useNoPCH);
2736 // if we have flags or defines for this config then
2738 if (!flags.empty() || !options.empty() || !configDefines.empty() ||
2739 !includes.empty() || compileAs || noWinRT || !options.empty() ||
2741 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
2742 cmIDEFlagTable const* flagtable = nullptr;
2743 const std::string& srclang = source->GetLanguage();
2744 if (srclang == "C" || srclang == "CXX") {
2745 flagtable = gg->GetClFlagTable();
2746 } else if (srclang == "ASM_MASM" &&
2747 this->GlobalGenerator->IsMasmEnabled()) {
2748 flagtable = gg->GetMasmFlagTable();
2749 } else if (lang == "ASM_NASM" &&
2750 this->GlobalGenerator->IsNasmEnabled()) {
2751 flagtable = gg->GetNasmFlagTable();
2752 } else if (srclang == "RC") {
2753 flagtable = gg->GetRcFlagTable();
2754 } else if (srclang == "CSharp") {
2755 flagtable = gg->GetCSharpFlagTable();
2757 cmGeneratorExpressionInterpreter genexInterpreter(
2758 this->LocalGenerator, config, this->GeneratorTarget, lang);
2759 cmVS10GeneratorOptions clOptions(
2760 this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
2763 clOptions.AddFlag("CompileAs", compileAs);
2766 clOptions.AddFlag("CompileAsWinRT", "false");
2768 if (configDependentFlags) {
2769 clOptions.Parse(genexInterpreter.Evaluate(flags, "COMPILE_FLAGS"));
2771 clOptions.Parse(flags);
2774 if (needsPCHFlags) {
2775 // Add precompile headers compile options.
2777 clOptions.AddFlag("PrecompiledHeader", "Create");
2778 std::string pchHeader =
2779 this->GeneratorTarget->GetPchHeader(config, lang);
2780 clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
2781 std::string pchFile =
2782 this->GeneratorTarget->GetPchFile(config, lang);
2783 clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
2784 clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2785 } else if (useNoPCH) {
2786 clOptions.AddFlag("PrecompiledHeader", "NotUsing");
2787 } else if (useSharedPCH) {
2788 std::string pchHeader =
2789 this->GeneratorTarget->GetPchHeader(config, lang);
2790 clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2791 } else if (useDifferentLangPCH) {
2792 clOptions.AddFlag("PrecompiledHeader", "Use");
2793 std::string pchHeader =
2794 this->GeneratorTarget->GetPchHeader(config, lang);
2795 clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
2796 std::string pchFile =
2797 this->GeneratorTarget->GetPchFile(config, lang);
2798 clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
2799 clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2803 if (!options.empty()) {
2804 std::string expandedOptions;
2805 if (configDependentOptions) {
2806 this->LocalGenerator->AppendCompileOptions(
2808 genexInterpreter.Evaluate(options, "COMPILE_OPTIONS"));
2810 this->LocalGenerator->AppendCompileOptions(expandedOptions, options);
2812 clOptions.Parse(expandedOptions);
2814 if (clOptions.HasFlag("DisableSpecificWarnings")) {
2815 clOptions.AppendFlag("DisableSpecificWarnings",
2816 "%(DisableSpecificWarnings)");
2818 if (clOptions.HasFlag("ForcedIncludeFiles")) {
2819 clOptions.AppendFlag("ForcedIncludeFiles", "%(ForcedIncludeFiles)");
2821 if (configDependentDefines) {
2822 clOptions.AddDefines(
2823 genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS"));
2825 clOptions.AddDefines(configDefines);
2827 std::vector<std::string> includeList;
2828 if (configDependentIncludes) {
2829 this->LocalGenerator->AppendIncludeDirectories(
2831 genexInterpreter.Evaluate(includes, "INCLUDE_DIRECTORIES"), *source);
2833 this->LocalGenerator->AppendIncludeDirectories(includeList, includes,
2836 clOptions.AddIncludes(includeList);
2837 clOptions.SetConfiguration(config);
2838 OptionsHelper oh(clOptions, e2);
2839 oh.PrependInheritedString("AdditionalOptions");
2840 oh.OutputAdditionalIncludeDirectories(lang);
2842 oh.OutputPreprocessorDefinitions(lang);
2845 if (this->IsXamlSource(source->GetFullPath())) {
2846 const std::string& fileName = source->GetFullPath();
2847 e2.Element("DependentUpon",
2848 fileName.substr(0, fileName.find_last_of(".")));
2850 if (this->ProjectType == VsProjectType::csproj) {
2851 std::string f = source->GetFullPath();
2852 using CsPropMap = std::map<std::string, std::string>;
2853 CsPropMap sourceFileTags;
2854 this->GetCSharpSourceProperties(&sf, sourceFileTags);
2855 // write source file specific tags
2856 if (!sourceFileTags.empty()) {
2857 this->WriteCSharpSourceProperties(e2, sourceFileTags);
2862 void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild(
2863 Elem& e2, std::vector<size_t> const& exclude_configs)
2865 for (size_t ci : exclude_configs) {
2866 e2.WritePlatformConfigTag("ExcludedFromBuild",
2867 "'$(Configuration)|$(Platform)'=='" +
2868 this->Configurations[ci] + "|" +
2869 this->Platform + "'",
2874 void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions(
2877 cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
2878 if (ttype > cmStateEnums::GLOBAL_TARGET) {
2881 if (this->ProjectType == VsProjectType::csproj) {
2885 Elem e1(e0, "PropertyGroup");
2886 e1.Element("_ProjectFileVersion", "10.0.20506.1");
2887 for (std::string const& config : this->Configurations) {
2888 const std::string cond = this->CalcCondition(config);
2890 if (ttype >= cmStateEnums::UTILITY) {
2891 e1.WritePlatformConfigTag(
2892 "IntDir", cond, "$(Platform)\\$(Configuration)\\$(ProjectName)\\");
2894 std::string intermediateDir = cmStrCat(
2895 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/',
2898 std::string targetNameFull;
2899 if (ttype == cmStateEnums::OBJECT_LIBRARY) {
2900 outDir = intermediateDir;
2901 targetNameFull = cmStrCat(this->GeneratorTarget->GetName(), ".lib");
2903 outDir = this->GeneratorTarget->GetDirectory(config) + "/";
2904 targetNameFull = this->GeneratorTarget->GetFullName(config);
2906 ConvertToWindowsSlash(intermediateDir);
2907 ConvertToWindowsSlash(outDir);
2909 e1.WritePlatformConfigTag("OutDir", cond, outDir);
2911 e1.WritePlatformConfigTag("IntDir", cond, intermediateDir);
2913 if (cmValue sdkExecutableDirectories = this->Makefile->GetDefinition(
2914 "CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES")) {
2915 e1.WritePlatformConfigTag("ExecutablePath", cond,
2916 *sdkExecutableDirectories);
2919 if (cmValue sdkIncludeDirectories = this->Makefile->GetDefinition(
2920 "CMAKE_VS_SDK_INCLUDE_DIRECTORIES")) {
2921 e1.WritePlatformConfigTag("IncludePath", cond, *sdkIncludeDirectories);
2924 if (cmValue sdkReferenceDirectories = this->Makefile->GetDefinition(
2925 "CMAKE_VS_SDK_REFERENCE_DIRECTORIES")) {
2926 e1.WritePlatformConfigTag("ReferencePath", cond,
2927 *sdkReferenceDirectories);
2930 if (cmValue sdkLibraryDirectories = this->Makefile->GetDefinition(
2931 "CMAKE_VS_SDK_LIBRARY_DIRECTORIES")) {
2932 e1.WritePlatformConfigTag("LibraryPath", cond, *sdkLibraryDirectories);
2935 if (cmValue sdkLibraryWDirectories = this->Makefile->GetDefinition(
2936 "CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES")) {
2937 e1.WritePlatformConfigTag("LibraryWPath", cond,
2938 *sdkLibraryWDirectories);
2941 if (cmValue sdkSourceDirectories =
2942 this->Makefile->GetDefinition("CMAKE_VS_SDK_SOURCE_DIRECTORIES")) {
2943 e1.WritePlatformConfigTag("SourcePath", cond, *sdkSourceDirectories);
2946 if (cmValue sdkExcludeDirectories = this->Makefile->GetDefinition(
2947 "CMAKE_VS_SDK_EXCLUDE_DIRECTORIES")) {
2948 e1.WritePlatformConfigTag("ExcludePath", cond, *sdkExcludeDirectories);
2952 cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
2953 e1.WritePlatformConfigTag("TargetName", cond, name);
2956 cmSystemTools::GetFilenameLastExtension(targetNameFull);
2958 // An empty TargetExt causes a default extension to be used.
2959 // A single "." appears to be treated as an empty extension.
2962 e1.WritePlatformConfigTag("TargetExt", cond, ext);
2964 this->OutputLinkIncremental(e1, config);
2967 if (ttype <= cmStateEnums::UTILITY) {
2968 if (cmValue workingDir = this->GeneratorTarget->GetProperty(
2969 "VS_DEBUGGER_WORKING_DIRECTORY")) {
2970 std::string genWorkingDir = cmGeneratorExpression::Evaluate(
2971 *workingDir, this->LocalGenerator, config);
2972 e1.WritePlatformConfigTag("LocalDebuggerWorkingDirectory", cond,
2976 if (cmValue environment =
2977 this->GeneratorTarget->GetProperty("VS_DEBUGGER_ENVIRONMENT")) {
2978 std::string genEnvironment = cmGeneratorExpression::Evaluate(
2979 *environment, this->LocalGenerator, config);
2980 e1.WritePlatformConfigTag("LocalDebuggerEnvironment", cond,
2984 if (cmValue debuggerCommand =
2985 this->GeneratorTarget->GetProperty("VS_DEBUGGER_COMMAND")) {
2986 std::string genDebuggerCommand = cmGeneratorExpression::Evaluate(
2987 *debuggerCommand, this->LocalGenerator, config);
2988 e1.WritePlatformConfigTag("LocalDebuggerCommand", cond,
2989 genDebuggerCommand);
2992 if (cmValue commandArguments = this->GeneratorTarget->GetProperty(
2993 "VS_DEBUGGER_COMMAND_ARGUMENTS")) {
2994 std::string genCommandArguments = cmGeneratorExpression::Evaluate(
2995 *commandArguments, this->LocalGenerator, config);
2996 e1.WritePlatformConfigTag("LocalDebuggerCommandArguments", cond,
2997 genCommandArguments);
3003 void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
3004 Elem& e1, std::string const& configName)
3006 if (!this->MSTools) {
3009 if (this->ProjectType == VsProjectType::csproj) {
3012 // static libraries and things greater than modules do not need
3013 // to set this option
3014 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
3015 this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
3018 Options& linkOptions = *(this->LinkOptions[configName]);
3019 const std::string cond = this->CalcCondition(configName);
3021 if (this->IPOEnabledConfigurations.count(configName) == 0) {
3022 const char* incremental = linkOptions.GetFlag("LinkIncremental");
3023 e1.WritePlatformConfigTag("LinkIncremental", cond,
3024 (incremental ? incremental : "true"));
3026 linkOptions.RemoveFlag("LinkIncremental");
3028 const char* manifest = linkOptions.GetFlag("GenerateManifest");
3029 e1.WritePlatformConfigTag("GenerateManifest", cond,
3030 (manifest ? manifest : "true"));
3031 linkOptions.RemoveFlag("GenerateManifest");
3033 // Some link options belong here. Use them now and remove them so that
3034 // WriteLinkOptions does not use them.
3035 static const std::vector<std::string> flags{ "LinkDelaySign",
3037 for (const std::string& flag : flags) {
3038 if (const char* value = linkOptions.GetFlag(flag)) {
3039 e1.WritePlatformConfigTag(flag, cond, value);
3040 linkOptions.RemoveFlag(flag);
3045 std::vector<std::string> cmVisualStudio10TargetGenerator::GetIncludes(
3046 std::string const& config, std::string const& lang) const
3048 std::vector<std::string> includes;
3049 this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
3051 for (std::string& i : includes) {
3052 ConvertToWindowsSlash(i);
3057 bool cmVisualStudio10TargetGenerator::ComputeClOptions()
3059 for (std::string const& c : this->Configurations) {
3060 if (!this->ComputeClOptions(c)) {
3067 bool cmVisualStudio10TargetGenerator::ComputeClOptions(
3068 std::string const& configName)
3070 // much of this was copied from here:
3071 // copied from cmLocalVisualStudio7Generator.cxx 805
3072 // TODO: Integrate code below with cmLocalVisualStudio7Generator.
3074 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3075 std::unique_ptr<Options> pOptions;
3076 switch (this->ProjectType) {
3077 case VsProjectType::vcxproj:
3078 pOptions = cm::make_unique<Options>(
3079 this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
3081 case VsProjectType::csproj:
3083 cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
3084 gg->GetCSharpFlagTable());
3089 Options& clOptions = *pOptions;
3092 const std::string& linkLanguage =
3093 this->GeneratorTarget->GetLinkerLanguage(configName);
3094 if (linkLanguage.empty()) {
3095 cmSystemTools::Error(
3096 "CMake can not determine linker language for target: " + this->Name);
3100 // Choose a language whose flags to use for ClCompile.
3101 static const char* clLangs[] = { "CXX", "C", "Fortran" };
3102 std::string langForClCompile;
3103 if (this->ProjectType == VsProjectType::csproj) {
3104 langForClCompile = "CSharp";
3105 } else if (cm::contains(clLangs, linkLanguage)) {
3106 langForClCompile = linkLanguage;
3108 std::set<std::string> languages;
3109 this->GeneratorTarget->GetLanguages(languages, configName);
3110 for (const char* l : clLangs) {
3111 if (languages.count(l)) {
3112 langForClCompile = l;
3117 this->LangForClCompile = langForClCompile;
3118 if (!langForClCompile.empty()) {
3119 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3120 langForClCompile, configName);
3121 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
3122 langForClCompile, configName);
3125 // Put the IPO enabled configurations into a set.
3126 if (this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName)) {
3127 this->IPOEnabledConfigurations.insert(configName);
3130 // Check if ASan is enabled.
3131 if (flags.find("/fsanitize=address") != std::string::npos) {
3132 this->ASanEnabledConfigurations.insert(configName);
3135 // Precompile Headers
3136 std::string pchHeader =
3137 this->GeneratorTarget->GetPchHeader(configName, linkLanguage);
3138 if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
3139 pchHeader.empty()) {
3140 clOptions.AddFlag("PrecompiledHeader", "NotUsing");
3141 } else if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
3142 !pchHeader.empty()) {
3143 clOptions.AddFlag("PrecompiledHeader", "Use");
3144 clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
3145 std::string pchFile =
3146 this->GeneratorTarget->GetPchFile(configName, linkLanguage);
3147 clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
3150 // Get preprocessor definitions for this directory.
3151 std::string defineFlags = this->Makefile->GetDefineFlags();
3152 if (this->MSTools) {
3153 if (this->ProjectType == VsProjectType::vcxproj) {
3154 clOptions.FixExceptionHandlingDefault();
3155 if (this->GlobalGenerator->GetVersion() >=
3156 cmGlobalVisualStudioGenerator::VSVersion::VS15) {
3157 // Toolsets that come with VS 2017 may now enable UseFullPaths
3158 // by default and there is no negative /FC option that projects
3159 // can use to switch it back. Older toolsets disable this by
3160 // default anyway so this will not hurt them. If the project
3161 // is using an explicit /FC option then parsing flags will
3162 // replace this setting with "true" below.
3163 clOptions.AddFlag("UseFullPaths", "false");
3165 clOptions.AddFlag("AssemblerListingLocation", "$(IntDir)");
3169 // check for managed C++ assembly compiler flag. This overrides any
3170 // /clr* compiler flags which may be defined in the flags variable(s).
3171 if (this->ProjectType != VsProjectType::csproj) {
3172 // Warn if /clr was added manually. This should not be done
3173 // anymore, because cmGeneratorTarget may not be aware that the
3174 // target uses C++/CLI.
3175 if (flags.find("/clr") != std::string::npos ||
3176 defineFlags.find("/clr") != std::string::npos) {
3177 if (configName == this->Configurations[0]) {
3178 std::string message = "For the target \"" +
3179 this->GeneratorTarget->GetName() +
3180 "\" the /clr compiler flag was added manually. " +
3181 "Set usage of C++/CLI by setting COMMON_LANGUAGE_RUNTIME "
3183 this->Makefile->IssueMessage(MessageType::WARNING, message);
3187 this->GeneratorTarget->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
3188 std::string clrString = *clr;
3189 if (!clrString.empty()) {
3190 clrString = ":" + clrString;
3192 flags += " /clr" + clrString;
3196 // Get includes for this target
3197 if (!this->LangForClCompile.empty()) {
3198 auto includeList = this->GetIncludes(configName, this->LangForClCompile);
3200 auto sysIncludeFlag = this->Makefile->GetDefinition(
3201 cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile));
3203 if (sysIncludeFlag) {
3204 bool gotOneSys = false;
3205 for (auto i : includeList) {
3206 cmSystemTools::ConvertToUnixSlashes(i);
3207 if (this->GeneratorTarget->IsSystemIncludeDirectory(
3208 i, configName, this->LangForClCompile)) {
3209 auto flag = cmTrimWhitespace(*sysIncludeFlag);
3210 if (this->MSTools) {
3211 cmSystemTools::ReplaceString(flag, "-external:I", "/external:I");
3213 clOptions.AppendFlagString("AdditionalOptions",
3214 cmStrCat(flag, " \"", i, '"'));
3217 clOptions.AddInclude(i);
3222 if (auto sysIncludeFlagWarning = this->Makefile->GetDefinition(
3223 cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile,
3225 flags = cmStrCat(flags, ' ', *sysIncludeFlagWarning);
3229 clOptions.AddIncludes(includeList);
3233 clOptions.Parse(flags);
3234 clOptions.Parse(defineFlags);
3235 std::vector<std::string> targetDefines;
3236 switch (this->ProjectType) {
3237 case VsProjectType::vcxproj:
3238 if (!langForClCompile.empty()) {
3239 this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3243 case VsProjectType::csproj:
3244 this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3246 cm::erase_if(targetDefines, [](std::string const& def) {
3247 return def.find('=') != std::string::npos;
3253 clOptions.AddDefines(targetDefines);
3255 if (this->ProjectType == VsProjectType::csproj) {
3256 clOptions.AppendFlag("DefineConstants", targetDefines);
3259 if (this->MSTools) {
3260 clOptions.SetVerboseMakefile(
3261 this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
3264 // Add C-specific flags expressible in a ClCompile meant for C++.
3265 if (langForClCompile == "CXX") {
3266 std::set<std::string> languages;
3267 this->GeneratorTarget->GetLanguages(languages, configName);
3268 if (languages.count("C")) {
3270 this->LocalGenerator->AddCompileOptions(flagsC, this->GeneratorTarget,
3272 Options optC(this->LocalGenerator, Options::Compiler,
3273 gg->GetClFlagTable());
3275 if (const char* stdC = optC.GetFlag("LanguageStandard_C")) {
3276 clOptions.AddFlag("LanguageStandard_C", stdC);
3281 // Add a definition for the configuration name.
3282 std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
3283 clOptions.AddDefine(configDefine);
3284 if (const std::string* exportMacro =
3285 this->GeneratorTarget->GetExportMacro()) {
3286 clOptions.AddDefine(*exportMacro);
3289 if (this->MSTools) {
3290 // If we have the VS_WINRT_COMPONENT set then force Compile as WinRT
3291 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
3292 clOptions.AddFlag("CompileAsWinRT", "true");
3293 // For WinRT components, add the _WINRT_DLL define to produce a lib
3294 if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
3295 this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
3296 clOptions.AddDefine("_WINRT_DLL");
3298 } else if (this->GlobalGenerator->TargetsWindowsStore() ||
3299 this->GlobalGenerator->TargetsWindowsPhone() ||
3300 this->Makefile->IsOn("CMAKE_VS_WINRT_BY_DEFAULT")) {
3301 if (!clOptions.IsWinRt()) {
3302 clOptions.AddFlag("CompileAsWinRT", "false");
3305 if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) {
3306 if (cmIsOn(winRT)) {
3307 this->TargetCompileAsWinRT = true;
3312 if (this->ProjectType != VsProjectType::csproj && clOptions.IsManaged()) {
3313 this->Managed = true;
3314 std::string managedType = clOptions.GetFlag("CompileAsManaged");
3315 if (managedType == "Safe" || managedType == "Pure") {
3316 // force empty calling convention if safe clr is used
3317 clOptions.AddFlag("CallingConvention", "");
3319 // The default values of these flags are incompatible to
3320 // managed assemblies. We have to force valid values if
3321 // the target is a managed C++ target.
3322 clOptions.AddFlag("ExceptionHandling", "Async");
3323 clOptions.AddFlag("BasicRuntimeChecks", "Default");
3325 if (this->ProjectType == VsProjectType::csproj) {
3326 // /nowin32manifest overrides /win32manifest: parameter
3327 if (clOptions.HasFlag("NoWin32Manifest")) {
3328 clOptions.RemoveFlag("ApplicationManifest");
3332 if (const char* s = clOptions.GetFlag("SpectreMitigation")) {
3333 this->SpectreMitigation[configName] = s;
3334 clOptions.RemoveFlag("SpectreMitigation");
3337 // Remove any target-wide -TC or -TP flag added by the project.
3338 // Such flags are unnecessary and break our model of language selection.
3339 if (langForClCompile == "C" || langForClCompile == "CXX") {
3340 clOptions.RemoveFlag("CompileAs");
3343 this->ClOptions[configName] = std::move(pOptions);
3347 void cmVisualStudio10TargetGenerator::WriteClOptions(
3348 Elem& e1, std::string const& configName)
3350 Options& clOptions = *(this->ClOptions[configName]);
3351 if (this->ProjectType == VsProjectType::csproj) {
3354 Elem e2(e1, "ClCompile");
3355 OptionsHelper oh(clOptions, e2);
3356 oh.PrependInheritedString("AdditionalOptions");
3357 oh.OutputAdditionalIncludeDirectories(this->LangForClCompile);
3359 oh.OutputPreprocessorDefinitions(this->LangForClCompile);
3361 if (this->NsightTegra) {
3362 if (cmValue processMax =
3363 this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) {
3364 e2.Element("ProcessMax", *processMax);
3368 if (this->Android) {
3369 e2.Element("ObjectFileName", "$(IntDir)%(filename).o");
3370 } else if (this->MSTools) {
3371 cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
3372 const char* toolset = this->GlobalGenerator->GetPlatformToolset();
3373 cmValue noCompileBatching =
3374 this->GeneratorTarget->GetProperty("VS_NO_COMPILE_BATCHING");
3375 if (noCompileBatching.IsOn() || (toolset && clangToolset.find(toolset))) {
3376 e2.Element("ObjectFileName", "$(IntDir)%(filename).obj");
3378 e2.Element("ObjectFileName", "$(IntDir)");
3381 // If not in debug mode, write the DebugInformationFormat field
3382 // without value so PDBs don't get generated uselessly. Each tag
3383 // goes on its own line because Visual Studio corrects it this
3384 // way when saving the project after CMake generates it.
3385 if (!clOptions.IsDebug()) {
3386 Elem e3(e2, "DebugInformationFormat");
3387 e3.SetHasElements();
3390 // Specify the compiler program database file if configured.
3391 std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
3393 if (this->GlobalGenerator->IsCudaEnabled()) {
3394 // CUDA does not quote paths with spaces correctly when forwarding
3395 // this to the host compiler. Use a relative path to avoid spaces.
3396 // FIXME: We can likely do this even when CUDA is not involved,
3397 // but for now we will make a minimal change.
3398 pdb = this->ConvertPath(pdb, true);
3400 ConvertToWindowsSlash(pdb);
3401 e2.Element("ProgramDataBaseFileName", pdb);
3404 // add AdditionalUsingDirectories
3405 if (this->AdditionalUsingDirectories.count(configName) > 0) {
3407 for (auto u : this->AdditionalUsingDirectories[configName]) {
3408 if (!dirs.empty()) {
3413 e2.Element("AdditionalUsingDirectories", dirs);
3418 bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
3420 for (std::string const& c : this->Configurations) {
3421 if (!this->ComputeRcOptions(c)) {
3428 bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
3429 std::string const& configName)
3431 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3432 auto pOptions = cm::make_unique<Options>(
3433 this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
3434 Options& rcOptions = *pOptions;
3436 std::string CONFIG = cmSystemTools::UpperCase(configName);
3437 std::string rcConfigFlagsVar = "CMAKE_RC_FLAGS_" + CONFIG;
3438 std::string flags = this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS") +
3439 " " + this->Makefile->GetSafeDefinition(rcConfigFlagsVar);
3441 rcOptions.Parse(flags);
3443 // For historical reasons, add the C preprocessor defines to RC.
3444 Options& clOptions = *(this->ClOptions[configName]);
3445 rcOptions.AddDefines(clOptions.GetDefines());
3447 // Get includes for this target
3448 rcOptions.AddIncludes(this->GetIncludes(configName, "RC"));
3450 this->RcOptions[configName] = std::move(pOptions);
3454 void cmVisualStudio10TargetGenerator::WriteRCOptions(
3455 Elem& e1, std::string const& configName)
3457 if (!this->MSTools) {
3460 Elem e2(e1, "ResourceCompile");
3462 OptionsHelper rcOptions(*(this->RcOptions[configName]), e2);
3463 rcOptions.OutputPreprocessorDefinitions("RC");
3464 rcOptions.OutputAdditionalIncludeDirectories("RC");
3465 rcOptions.PrependInheritedString("AdditionalOptions");
3466 rcOptions.OutputFlagMap();
3469 bool cmVisualStudio10TargetGenerator::ComputeCudaOptions()
3471 if (!this->GlobalGenerator->IsCudaEnabled()) {
3474 for (std::string const& c : this->Configurations) {
3475 if (this->GeneratorTarget->IsLanguageUsed("CUDA", c) &&
3476 !this->ComputeCudaOptions(c)) {
3483 bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
3484 std::string const& configName)
3486 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3487 auto pOptions = cm::make_unique<Options>(
3488 this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
3489 Options& cudaOptions = *pOptions;
3491 auto cudaVersion = this->GlobalGenerator->GetPlatformToolsetCudaString();
3493 // Get compile flags for CUDA in this directory.
3495 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget, "CUDA",
3497 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, "CUDA",
3500 // Get preprocessor definitions for this directory.
3501 std::string defineFlags = this->Makefile->GetDefineFlags();
3503 cudaOptions.Parse(flags);
3504 cudaOptions.Parse(defineFlags);
3505 cudaOptions.ParseFinish();
3507 // If we haven't explicitly enabled GPU debug information
3508 // explicitly disable it
3509 if (!cudaOptions.HasFlag("GPUDebugInfo")) {
3510 cudaOptions.AddFlag("GPUDebugInfo", "false");
3513 // The extension on object libraries the CUDA gives isn't
3514 // consistent with how MSVC generates object libraries for C+, so set
3515 // the default to not have any extension
3516 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).obj");
3518 if (this->GeneratorTarget->GetPropertyAsBool("CUDA_SEPARABLE_COMPILATION")) {
3519 cudaOptions.AddFlag("GenerateRelocatableDeviceCode", "true");
3522 if (this->GeneratorTarget->GetPropertyAsBool("CUDA_PTX_COMPILATION")) {
3523 cudaOptions.AddFlag("NvccCompilation", "ptx");
3524 // We drop the %(Extension) component as CMake expects all PTX files
3525 // to not have the source file extension at all
3526 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
3529 if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
3530 cudaVersion, "9.0") &&
3531 cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, cudaVersion,
3533 // The DriverApi flag before 11.5 ( verified back to 9.0 ) which controls
3534 // PTX compilation doesn't propagate user defines causing
3535 // target_compile_definitions to behave differently for VS +
3536 // PTX compared to other generators so we patch the rules
3537 // to normalize behavior
3538 cudaOptions.AddFlag("DriverApiCommandLineTemplate",
3539 "%(BaseCommandLineTemplate) [CompileOut] [FastMath] "
3540 "[Defines] \"%(FullPath)\"");
3545 cmSystemTools::VersionCompareGreaterEq(
3546 "8.0", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
3547 // Explicitly state that we want this file to be treated as a
3548 // CUDA file no matter what the file extensions is
3549 // This is only needed for < CUDA 9
3550 cudaOptions.AppendFlagString("AdditionalOptions", "-x cu");
3553 // Specify the compiler program database file if configured.
3554 std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
3556 // CUDA does not make the directory if it is non-standard.
3557 std::string const pdbDir = cmSystemTools::GetFilenamePath(pdb);
3558 cmSystemTools::MakeDirectory(pdbDir);
3559 if (cmSystemTools::VersionCompareGreaterEq(
3560 "9.2", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
3561 // CUDA does not have a field for this and does not honor the
3562 // ProgramDataBaseFileName field in ClCompile. Work around this
3563 // limitation by creating the directory and passing the flag ourselves.
3564 pdb = this->ConvertPath(pdb, true);
3565 ConvertToWindowsSlash(pdb);
3566 std::string const clFd = "-Xcompiler=\"-Fd\\\"" + pdb + "\\\"\"";
3567 cudaOptions.AppendFlagString("AdditionalOptions", clFd);
3571 // CUDA automatically passes the proper '--machine' flag to nvcc
3572 // for the current architecture, but does not reflect this default
3573 // in the user-visible IDE settings. Set it explicitly.
3574 if (this->Platform == "x64") {
3575 cudaOptions.AddFlag("TargetMachinePlatform", "64");
3578 // Convert the host compiler options to the toolset's abstractions
3579 // using a secondary flag table.
3580 cudaOptions.ClearTables();
3581 cudaOptions.AddTable(gg->GetCudaHostFlagTable());
3582 cudaOptions.Reparse("AdditionalCompilerOptions");
3584 // `CUDA 8.0.targets` places AdditionalCompilerOptions before nvcc!
3585 // Pass them through -Xcompiler in AdditionalOptions instead.
3586 if (const char* acoPtr = cudaOptions.GetFlag("AdditionalCompilerOptions")) {
3587 std::string aco = acoPtr;
3588 cudaOptions.RemoveFlag("AdditionalCompilerOptions");
3590 aco = this->LocalGenerator->EscapeForShell(aco, false);
3591 cudaOptions.AppendFlagString("AdditionalOptions", "-Xcompiler=" + aco);
3595 cudaOptions.FixCudaCodeGeneration();
3597 std::vector<std::string> targetDefines;
3598 this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3600 cudaOptions.AddDefines(targetDefines);
3602 // Add a definition for the configuration name.
3603 std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
3604 cudaOptions.AddDefine(configDefine);
3605 if (const std::string* exportMacro =
3606 this->GeneratorTarget->GetExportMacro()) {
3607 cudaOptions.AddDefine(*exportMacro);
3610 // Get includes for this target
3611 cudaOptions.AddIncludes(this->GetIncludes(configName, "CUDA"));
3612 cudaOptions.AddFlag("UseHostInclude", "false");
3614 // Add runtime library selection flag.
3615 std::string const& cudaRuntime =
3616 this->GeneratorTarget->GetRuntimeLinkLibrary("CUDA", configName);
3617 if (cudaRuntime == "STATIC") {
3618 cudaOptions.AddFlag("CudaRuntime", "Static");
3619 } else if (cudaRuntime == "SHARED") {
3620 cudaOptions.AddFlag("CudaRuntime", "Shared");
3621 } else if (cudaRuntime == "NONE") {
3622 cudaOptions.AddFlag("CudaRuntime", "None");
3625 this->CudaOptions[configName] = std::move(pOptions);
3629 void cmVisualStudio10TargetGenerator::WriteCudaOptions(
3630 Elem& e1, std::string const& configName)
3632 if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled() ||
3633 !this->GeneratorTarget->IsLanguageUsed("CUDA", configName)) {
3636 Elem e2(e1, "CudaCompile");
3638 OptionsHelper cudaOptions(*(this->CudaOptions[configName]), e2);
3639 cudaOptions.OutputAdditionalIncludeDirectories("CUDA");
3640 cudaOptions.OutputPreprocessorDefinitions("CUDA");
3641 cudaOptions.PrependInheritedString("AdditionalOptions");
3642 cudaOptions.OutputFlagMap();
3645 bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
3647 if (!this->GlobalGenerator->IsCudaEnabled()) {
3650 for (std::string const& c : this->Configurations) {
3651 if (!this->ComputeCudaLinkOptions(c)) {
3658 bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
3659 std::string const& configName)
3661 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3662 auto pOptions = cm::make_unique<Options>(
3663 this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
3664 Options& cudaLinkOptions = *pOptions;
3666 cmGeneratorTarget::DeviceLinkSetter setter(*this->GeneratorTarget);
3668 // Determine if we need to do a device link
3669 const bool doDeviceLinking = requireDeviceLinking(
3670 *this->GeneratorTarget, *this->LocalGenerator, configName);
3672 cudaLinkOptions.AddFlag("PerformDeviceLink",
3673 doDeviceLinking ? "true" : "false");
3675 // Add extra flags for device linking
3676 cudaLinkOptions.AppendFlagString(
3677 "AdditionalOptions",
3678 this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_FLAGS"));
3679 cudaLinkOptions.AppendFlagString(
3680 "AdditionalOptions",
3681 this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS"));
3683 std::vector<std::string> linkOpts;
3684 std::string linkFlags;
3685 this->GeneratorTarget->GetLinkOptions(linkOpts, configName, "CUDA");
3686 // LINK_OPTIONS are escaped.
3687 this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
3688 cudaLinkOptions.AppendFlagString("AdditionalOptions", linkFlags);
3690 // For static libraries that have device linking enabled compute
3692 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY &&
3694 cmComputeLinkInformation* pcli =
3695 this->GeneratorTarget->GetLinkInformation(configName);
3697 cmSystemTools::Error(
3698 "CMake can not compute cmComputeLinkInformation for target: " +
3703 cmComputeLinkInformation& cli = *pcli;
3704 cmLinkLineDeviceComputer computer(
3705 this->LocalGenerator,
3706 this->LocalGenerator->GetStateSnapshot().GetDirectory());
3707 std::vector<BT<std::string>> btLibVec;
3708 computer.ComputeLinkLibraries(cli, std::string{}, btLibVec);
3709 std::vector<std::string> libVec;
3710 for (auto const& item : btLibVec) {
3711 libVec.emplace_back(item.Value);
3714 cudaLinkOptions.AddFlag("AdditionalDependencies", libVec);
3717 this->CudaLinkOptions[configName] = std::move(pOptions);
3721 void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
3722 Elem& e1, std::string const& configName)
3724 if (this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
3728 if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
3732 Elem e2(e1, "CudaLink");
3733 OptionsHelper cudaLinkOptions(*(this->CudaLinkOptions[configName]), e2);
3734 cudaLinkOptions.OutputFlagMap();
3737 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
3739 if (!this->GlobalGenerator->IsMasmEnabled()) {
3742 for (std::string const& c : this->Configurations) {
3743 if (!this->ComputeMasmOptions(c)) {
3750 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
3751 std::string const& configName)
3753 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3754 auto pOptions = cm::make_unique<Options>(
3755 this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
3756 Options& masmOptions = *pOptions;
3759 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3760 "ASM_MASM", configName);
3762 masmOptions.Parse(flags);
3764 // Get includes for this target
3765 masmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MASM"));
3767 this->MasmOptions[configName] = std::move(pOptions);
3771 void cmVisualStudio10TargetGenerator::WriteMasmOptions(
3772 Elem& e1, std::string const& configName)
3774 if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
3777 Elem e2(e1, "MASM");
3779 // Preprocessor definitions and includes are shared with clOptions.
3780 OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
3781 clOptions.OutputPreprocessorDefinitions("ASM_MASM");
3783 OptionsHelper masmOptions(*(this->MasmOptions[configName]), e2);
3784 masmOptions.OutputAdditionalIncludeDirectories("ASM_MASM");
3785 masmOptions.PrependInheritedString("AdditionalOptions");
3786 masmOptions.OutputFlagMap();
3789 bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
3791 if (!this->GlobalGenerator->IsNasmEnabled()) {
3794 for (std::string const& c : this->Configurations) {
3795 if (!this->ComputeNasmOptions(c)) {
3802 bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
3803 std::string const& configName)
3805 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3806 auto pOptions = cm::make_unique<Options>(
3807 this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
3808 Options& nasmOptions = *pOptions;
3811 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3812 "ASM_NASM", configName);
3814 flags += this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_OBJECT_FORMAT");
3815 nasmOptions.Parse(flags);
3817 // Get includes for this target
3818 nasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_NASM"));
3820 this->NasmOptions[configName] = std::move(pOptions);
3824 void cmVisualStudio10TargetGenerator::WriteNasmOptions(
3825 Elem& e1, std::string const& configName)
3827 if (!this->GlobalGenerator->IsNasmEnabled()) {
3830 Elem e2(e1, "NASM");
3832 OptionsHelper nasmOptions(*(this->NasmOptions[configName]), e2);
3833 nasmOptions.OutputAdditionalIncludeDirectories("ASM_NASM");
3834 nasmOptions.OutputFlagMap();
3835 nasmOptions.PrependInheritedString("AdditionalOptions");
3836 nasmOptions.OutputPreprocessorDefinitions("ASM_NASM");
3838 // Preprocessor definitions and includes are shared with clOptions.
3839 OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
3840 clOptions.OutputPreprocessorDefinitions("ASM_NASM");
3843 void cmVisualStudio10TargetGenerator::WriteLibOptions(
3844 Elem& e1, std::string const& config)
3846 if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
3847 this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
3851 const std::string& linkLanguage =
3852 this->GeneratorTarget->GetLinkClosure(config)->LinkerLanguage;
3854 std::string libflags;
3855 this->LocalGenerator->GetStaticLibraryFlags(libflags, config, linkLanguage,
3856 this->GeneratorTarget);
3857 if (!libflags.empty()) {
3859 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3860 cmVS10GeneratorOptions libOptions(this->LocalGenerator,
3861 cmVisualStudioGeneratorOptions::Linker,
3862 gg->GetLibFlagTable(), this);
3863 libOptions.Parse(libflags);
3864 OptionsHelper oh(libOptions, e2);
3865 oh.PrependInheritedString("AdditionalOptions");
3869 // We cannot generate metadata for static libraries. WindowsPhone
3870 // and WindowsStore tools look at GenerateWindowsMetadata in the
3871 // Link tool options even for static libraries.
3872 if (this->GlobalGenerator->TargetsWindowsPhone() ||
3873 this->GlobalGenerator->TargetsWindowsStore()) {
3874 Elem e2(e1, "Link");
3875 e2.Element("GenerateWindowsMetadata", "false");
3879 void cmVisualStudio10TargetGenerator::WriteManifestOptions(
3880 Elem& e1, std::string const& config)
3882 if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
3883 this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
3884 this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
3888 std::vector<cmSourceFile const*> manifest_srcs;
3889 this->GeneratorTarget->GetManifests(manifest_srcs, config);
3891 cmValue dpiAware = this->GeneratorTarget->GetProperty("VS_DPI_AWARE");
3893 if (!manifest_srcs.empty() || dpiAware) {
3894 Elem e2(e1, "Manifest");
3895 if (!manifest_srcs.empty()) {
3896 std::ostringstream oss;
3897 for (cmSourceFile const* mi : manifest_srcs) {
3898 std::string m = this->ConvertPath(mi->GetFullPath(), false);
3899 ConvertToWindowsSlash(m);
3902 e2.Element("AdditionalManifestFiles", oss.str());
3905 if (*dpiAware == "PerMonitor") {
3906 e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware");
3907 } else if (cmIsOn(*dpiAware)) {
3908 e2.Element("EnableDpiAwareness", "true");
3909 } else if (cmIsOff(*dpiAware)) {
3910 e2.Element("EnableDpiAwareness", "false");
3912 cmSystemTools::Error("Bad parameter for VS_DPI_AWARE: " + *dpiAware);
3918 void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
3919 Elem& e1, std::string const& configName)
3921 // Look through the sources for AndroidManifest.xml and use
3922 // its location as the root source directory.
3923 std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
3925 for (cmGeneratorTarget::AllConfigSource const& source :
3926 this->GeneratorTarget->GetAllConfigSources()) {
3927 if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
3928 "androidmanifest.xml" ==
3929 cmSystemTools::LowerCase(source.Source->GetLocation().GetName())) {
3930 rootDir = source.Source->GetLocation().GetDirectory();
3936 // Tell MSBuild to launch Ant.
3937 Elem e2(e1, "AntBuild");
3939 std::string antBuildPath = rootDir;
3940 ConvertToWindowsSlash(antBuildPath);
3941 e2.Element("AntBuildPath", antBuildPath);
3944 if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
3945 e2.Element("SkipAntStep", "true");
3948 if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
3949 e2.Element("EnableProGuard", "true");
3952 if (cmValue proGuardConfigLocation =
3953 this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
3954 e2.Element("ProGuardConfigLocation", *proGuardConfigLocation);
3957 if (cmValue securePropertiesLocation =
3958 this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
3959 e2.Element("SecurePropertiesLocation", *securePropertiesLocation);
3962 if (cmValue nativeLibDirectoriesExpression =
3963 this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
3964 std::string nativeLibDirs = cmGeneratorExpression::Evaluate(
3965 *nativeLibDirectoriesExpression, this->LocalGenerator, configName);
3966 e2.Element("NativeLibDirectories", nativeLibDirs);
3969 if (cmValue nativeLibDependenciesExpression =
3970 this->GeneratorTarget->GetProperty(
3971 "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
3972 std::string nativeLibDeps = cmGeneratorExpression::Evaluate(
3973 *nativeLibDependenciesExpression, this->LocalGenerator, configName);
3974 e2.Element("NativeLibDependencies", nativeLibDeps);
3977 if (cmValue javaSourceDir =
3978 this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
3979 e2.Element("JavaSourceDir", *javaSourceDir);
3982 if (cmValue jarDirectoriesExpression =
3983 this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
3984 std::string jarDirectories = cmGeneratorExpression::Evaluate(
3985 *jarDirectoriesExpression, this->LocalGenerator, configName);
3986 e2.Element("JarDirectories", jarDirectories);
3989 if (cmValue jarDeps =
3990 this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
3991 e2.Element("JarDependencies", *jarDeps);
3994 if (cmValue assetsDirectories =
3995 this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
3996 e2.Element("AssetsDirectories", *assetsDirectories);
4000 std::string manifest_xml = rootDir + "/AndroidManifest.xml";
4001 ConvertToWindowsSlash(manifest_xml);
4002 e2.Element("AndroidManifestLocation", manifest_xml);
4005 if (cmValue antAdditionalOptions =
4006 this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
4007 e2.Element("AdditionalOptions",
4008 *antAdditionalOptions + " %(AdditionalOptions)");
4012 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
4014 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
4015 this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
4016 this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
4017 for (std::string const& c : this->Configurations) {
4018 if (!this->ComputeLinkOptions(c)) {
4026 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
4027 std::string const& config)
4029 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4030 auto pOptions = cm::make_unique<Options>(
4031 this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this);
4032 Options& linkOptions = *pOptions;
4034 cmGeneratorTarget::LinkClosure const* linkClosure =
4035 this->GeneratorTarget->GetLinkClosure(config);
4037 const std::string& linkLanguage = linkClosure->LinkerLanguage;
4038 if (linkLanguage.empty()) {
4039 cmSystemTools::Error(
4040 "CMake can not determine linker language for target: " + this->Name);
4044 std::string CONFIG = cmSystemTools::UpperCase(config);
4046 const char* linkType = "SHARED";
4047 if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
4048 linkType = "MODULE";
4050 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4054 std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS");
4056 flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase);
4057 std::string linkFlagVar = linkFlagVarBase + "_" + CONFIG;
4059 flags += this->Makefile->GetRequiredDefinition(linkFlagVar);
4060 cmValue targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS");
4061 if (targetLinkFlags) {
4063 flags += *targetLinkFlags;
4065 std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG);
4066 if (cmValue flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) {
4068 flags += *flagsConfig;
4071 std::vector<std::string> opts;
4072 this->GeneratorTarget->GetLinkOptions(opts, config, linkLanguage);
4073 // LINK_OPTIONS are escaped.
4074 this->LocalGenerator->AppendCompileOptions(flags, opts);
4076 cmComputeLinkInformation* pcli =
4077 this->GeneratorTarget->GetLinkInformation(config);
4079 cmSystemTools::Error(
4080 "CMake can not compute cmComputeLinkInformation for target: " +
4084 cmComputeLinkInformation& cli = *pcli;
4086 std::vector<std::string> libVec;
4087 std::vector<std::string> vsTargetVec;
4088 this->AddLibraries(cli, libVec, vsTargetVec, config);
4089 std::string standardLibsVar =
4090 cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
4091 std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar);
4092 cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
4093 linkOptions.AddFlag("AdditionalDependencies", libVec);
4095 // Populate TargetsFileAndConfigsVec
4096 for (std::string const& ti : vsTargetVec) {
4097 this->AddTargetsFileAndConfigPair(ti, config);
4100 std::vector<std::string> const& ldirs = cli.GetDirectories();
4101 std::vector<std::string> linkDirs;
4102 for (std::string const& d : ldirs) {
4103 // first just full path
4104 linkDirs.push_back(d);
4105 // next path with configuration type Debug, Release, etc
4106 linkDirs.push_back(d + "/$(Configuration)");
4108 linkDirs.push_back("%(AdditionalLibraryDirectories)");
4109 linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
4111 cmGeneratorTarget::Names targetNames;
4112 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4113 targetNames = this->GeneratorTarget->GetExecutableNames(config);
4115 targetNames = this->GeneratorTarget->GetLibraryNames(config);
4118 if (this->MSTools) {
4119 if (this->GeneratorTarget->IsWin32Executable(config)) {
4120 if (this->GlobalGenerator->TargetsWindowsCE()) {
4121 linkOptions.AddFlag("SubSystem", "WindowsCE");
4122 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4123 if (this->ClOptions[config]->UsingUnicode()) {
4124 linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
4126 linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
4130 linkOptions.AddFlag("SubSystem", "Windows");
4133 if (this->GlobalGenerator->TargetsWindowsCE()) {
4134 linkOptions.AddFlag("SubSystem", "WindowsCE");
4135 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4136 if (this->ClOptions[config]->UsingUnicode()) {
4137 linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
4139 linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
4143 linkOptions.AddFlag("SubSystem", "Console");
4147 if (cmValue stackVal = this->Makefile->GetDefinition(
4148 "CMAKE_" + linkLanguage + "_STACK_SIZE")) {
4149 linkOptions.AddFlag("StackReserveSize", *stackVal);
4152 linkOptions.AddFlag("GenerateDebugInformation", "false");
4154 std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config),
4155 '/', targetNames.PDB);
4156 if (!targetNames.ImportLibrary.empty()) {
4158 cmStrCat(this->GeneratorTarget->GetDirectory(
4159 config, cmStateEnums::ImportLibraryArtifact),
4160 '/', targetNames.ImportLibrary);
4162 linkOptions.AddFlag("ImportLibrary", imLib);
4164 linkOptions.AddFlag("ProgramDataBaseFile", pdb);
4166 // A Windows Runtime component uses internal .NET metadata,
4167 // so does not have an import library.
4168 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
4169 this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
4170 linkOptions.AddFlag("GenerateWindowsMetadata", "true");
4171 } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
4172 this->GlobalGenerator->TargetsWindowsStore()) {
4173 // WindowsPhone and WindowsStore components are in an app container
4174 // and produce WindowsMetadata. If we are not producing a WINRT
4175 // component, then do not generate the metadata here.
4176 linkOptions.AddFlag("GenerateWindowsMetadata", "false");
4179 if (this->GlobalGenerator->TargetsWindowsPhone() &&
4180 this->GlobalGenerator->GetSystemVersion() == "8.0") {
4181 // WindowsPhone 8.0 does not have ole32.
4182 linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
4184 } else if (this->NsightTegra) {
4185 linkOptions.AddFlag("SoName", targetNames.SharedObject);
4188 linkOptions.Parse(flags);
4189 linkOptions.FixManifestUACFlags();
4191 if (this->MSTools) {
4192 cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
4193 this->GeneratorTarget->GetModuleDefinitionInfo(config);
4194 if (mdi && !mdi->DefFile.empty()) {
4195 linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile);
4197 linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
4198 "%(IgnoreSpecificDefaultLibraries)");
4201 // VS 2015 without all updates has a v140 toolset whose
4202 // GenerateDebugInformation expects No/Debug instead of false/true.
4203 if (gg->GetPlatformToolsetNeedsDebugEnum()) {
4204 if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
4205 if (strcmp(debug, "false") == 0) {
4206 linkOptions.AddFlag("GenerateDebugInformation", "No");
4207 } else if (strcmp(debug, "true") == 0) {
4208 linkOptions.AddFlag("GenerateDebugInformation", "Debug");
4213 // Managed code cannot be linked with /DEBUG:FASTLINK
4214 if (this->Managed) {
4215 if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
4216 if (strcmp(debug, "DebugFastLink") == 0) {
4217 linkOptions.AddFlag("GenerateDebugInformation", "Debug");
4222 this->LinkOptions[config] = std::move(pOptions);
4226 bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
4228 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
4229 for (std::string const& c : this->Configurations) {
4230 if (!this->ComputeLibOptions(c)) {
4238 bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
4239 std::string const& config)
4241 cmComputeLinkInformation* pcli =
4242 this->GeneratorTarget->GetLinkInformation(config);
4244 cmSystemTools::Error(
4245 "CMake can not compute cmComputeLinkInformation for target: " +
4250 cmComputeLinkInformation& cli = *pcli;
4251 using ItemVector = cmComputeLinkInformation::ItemVector;
4252 const ItemVector& libs = cli.GetItems();
4253 for (cmComputeLinkInformation::Item const& l : libs) {
4254 if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
4255 cmVS10IsTargetsFile(l.Value.Value)) {
4257 this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
4258 ConvertToWindowsSlash(path);
4259 this->AddTargetsFileAndConfigPair(path, config);
4266 void cmVisualStudio10TargetGenerator::WriteLinkOptions(
4267 Elem& e1, std::string const& config)
4269 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
4270 this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
4273 if (this->ProjectType == VsProjectType::csproj) {
4278 Elem e2(e1, "Link");
4279 OptionsHelper linkOptions(*(this->LinkOptions[config]), e2);
4280 linkOptions.PrependInheritedString("AdditionalOptions");
4281 linkOptions.OutputFlagMap();
4284 if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
4285 this->GeneratorTarget)) {
4286 Elem e2(e1, "ProjectReference");
4287 e2.Element("LinkLibraryDependencies", "false");
4291 void cmVisualStudio10TargetGenerator::AddLibraries(
4292 const cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
4293 std::vector<std::string>& vsTargetVec, const std::string& config)
4295 using ItemVector = cmComputeLinkInformation::ItemVector;
4296 ItemVector const& libs = cli.GetItems();
4297 for (cmComputeLinkInformation::Item const& l : libs) {
4299 auto managedType = l.Target->GetManagedType(config);
4300 if (managedType != cmGeneratorTarget::ManagedType::Native &&
4301 this->GeneratorTarget->GetManagedType(config) !=
4302 cmGeneratorTarget::ManagedType::Native &&
4303 l.Target->IsImported() &&
4304 l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
4305 auto location = l.Target->GetFullPath(config);
4306 if (!location.empty()) {
4307 ConvertToWindowsSlash(location);
4308 switch (this->ProjectType) {
4309 case VsProjectType::csproj:
4310 // If the target we want to "link" to is an imported managed
4311 // target and this is a C# project, we add a hint reference. This
4312 // reference is written to project file in
4313 // WriteDotNetReferences().
4314 this->DotNetHintReferences[config].push_back(
4315 DotNetHintReference(l.Target->GetName(), location));
4317 case VsProjectType::vcxproj:
4318 // Add path of assembly to list of using-directories, so the
4319 // managed assembly can be used by '#using <assembly.dll>' in
4321 this->AdditionalUsingDirectories[config].insert(
4322 cmSystemTools::GetFilenamePath(location));
4325 // In .proj files, we wouldn't be referencing libraries.
4330 // Do not allow C# targets to be added to the LIB listing. LIB files are
4331 // used for linking C++ dependencies. C# libraries do not have lib files.
4332 // Instead, they compile down to C# reference libraries (DLL files). The
4333 // `<ProjectReference>` elements added to the vcxproj are enough for the
4334 // IDE to deduce the DLL file required by other C# projects that need its
4335 // reference library.
4336 if (managedType == cmGeneratorTarget::ManagedType::Managed) {
4341 if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
4343 this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
4344 ConvertToWindowsSlash(path);
4345 if (cmVS10IsTargetsFile(l.Value.Value)) {
4346 vsTargetVec.push_back(path);
4348 libVec.push_back(l.HasFeature() ? l.GetFormattedItem(path).Value
4351 } else if (!l.Target ||
4352 l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
4353 libVec.push_back(l.Value.Value);
4358 void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
4359 std::string const& targetsFile, std::string const& config)
4361 for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) {
4362 if (cmSystemTools::ComparePath(targetsFile, i.File)) {
4363 if (!cm::contains(i.Configs, config)) {
4364 i.Configs.push_back(config);
4369 TargetsFileAndConfigs entry;
4370 entry.File = targetsFile;
4371 entry.Configs.push_back(config);
4372 this->TargetsFileAndConfigsVec.push_back(entry);
4375 void cmVisualStudio10TargetGenerator::WriteMidlOptions(
4376 Elem& e1, std::string const& configName)
4378 if (!this->MSTools) {
4381 if (this->ProjectType == VsProjectType::csproj) {
4384 if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
4388 // This processes *any* of the .idl files specified in the project's file
4389 // list (and passed as the item metadata %(Filename) expressing the rule
4390 // input filename) into output files at the per-config *build* dir
4391 // ($(IntDir)) each.
4393 // IOW, this MIDL section is intended to provide a fully generic syntax
4394 // content suitable for most cases (read: if you get errors, then it's quite
4395 // probable that the error is on your side of the .idl setup).
4397 // Also, note that the marked-as-generated _i.c file in the Visual Studio
4398 // generator case needs to be referred to as $(IntDir)\foo_i.c at the
4399 // project's file list, otherwise the compiler-side processing won't pick it
4400 // up (for non-directory form, it ends up looking in project binary dir
4401 // only). Perhaps there's something to be done to make this more automatic
4402 // on the CMake side?
4403 std::vector<std::string> const includes =
4404 this->GetIncludes(configName, "MIDL");
4405 std::ostringstream oss;
4406 for (std::string const& i : includes) {
4409 oss << "%(AdditionalIncludeDirectories)";
4411 Elem e2(e1, "Midl");
4412 e2.Element("AdditionalIncludeDirectories", oss.str());
4413 e2.Element("OutputDirectory", "$(ProjectDir)/$(IntDir)");
4414 e2.Element("HeaderFileName", "%(Filename).h");
4415 e2.Element("TypeLibraryName", "%(Filename).tlb");
4416 e2.Element("InterfaceIdentifierFileName", "%(Filename)_i.c");
4417 e2.Element("ProxyFileName", "%(Filename)_p.c");
4420 void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups(Elem& e0)
4422 if (this->ProjectType == VsProjectType::csproj) {
4425 for (const std::string& c : this->Configurations) {
4426 Elem e1(e0, "ItemDefinitionGroup");
4427 e1.Attribute("Condition", this->CalcCondition(c));
4429 // output cl compile flags <ClCompile></ClCompile>
4430 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
4431 this->WriteClOptions(e1, c);
4432 // output rc compile flags <ResourceCompile></ResourceCompile>
4433 this->WriteRCOptions(e1, c);
4434 this->WriteCudaOptions(e1, c);
4435 this->WriteMasmOptions(e1, c);
4436 this->WriteNasmOptions(e1, c);
4438 // output midl flags <Midl></Midl>
4439 this->WriteMidlOptions(e1, c);
4441 if (this->ProjectType != VsProjectType::csproj) {
4442 this->WriteEvents(e1, c);
4444 // output link flags <Link></Link>
4445 this->WriteLinkOptions(e1, c);
4446 this->WriteCudaLinkOptions(e1, c);
4447 // output lib flags <Lib></Lib>
4448 this->WriteLibOptions(e1, c);
4449 // output manifest flags <Manifest></Manifest>
4450 this->WriteManifestOptions(e1, c);
4451 if (this->NsightTegra &&
4452 this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
4453 this->WriteAntBuildOptions(e1, c);
4458 void cmVisualStudio10TargetGenerator::WriteEvents(
4459 Elem& e1, std::string const& configName)
4461 bool addedPrelink = false;
4462 cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
4463 this->GeneratorTarget->GetModuleDefinitionInfo(configName);
4464 if (mdi && mdi->DefFileGenerated) {
4465 addedPrelink = true;
4466 std::vector<cmCustomCommand> commands =
4467 this->GeneratorTarget->GetPreLinkCommands();
4468 this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
4469 commands, configName);
4470 this->WriteEvent(e1, "PreLinkEvent", commands, configName);
4472 if (!addedPrelink) {
4473 this->WriteEvent(e1, "PreLinkEvent",
4474 this->GeneratorTarget->GetPreLinkCommands(), configName);
4476 this->WriteEvent(e1, "PreBuildEvent",
4477 this->GeneratorTarget->GetPreBuildCommands(), configName);
4478 this->WriteEvent(e1, "PostBuildEvent",
4479 this->GeneratorTarget->GetPostBuildCommands(), configName);
4482 void cmVisualStudio10TargetGenerator::WriteEvent(
4483 Elem& e1, const std::string& name,
4484 std::vector<cmCustomCommand> const& commands, std::string const& configName)
4486 if (commands.empty()) {
4489 cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
4491 const char* pre = "";
4492 std::string comment;
4493 bool stdPipesUTF8 = false;
4494 for (cmCustomCommand const& cc : commands) {
4495 cmCustomCommandGenerator ccg(cc, configName, lg);
4496 if (!ccg.HasOnlyEmptyCommandLines()) {
4498 comment += lg->ConstructComment(ccg);
4501 script += lg->ConstructScript(ccg);
4503 stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
4506 if (!script.empty()) {
4507 script += lg->FinishConstructScript(this->ProjectType);
4509 comment = cmVS10EscapeComment(comment);
4510 if (this->ProjectType != VsProjectType::csproj) {
4513 this->WriteStdOutEncodingUtf8(e2);
4515 e2.Element("Message", comment);
4516 e2.Element("Command", script);
4518 std::string strippedComment = comment;
4519 strippedComment.erase(
4520 std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
4521 strippedComment.end());
4522 std::ostringstream oss;
4523 if (!comment.empty() && !strippedComment.empty()) {
4524 oss << "echo " << comment << "\n";
4526 oss << script << "\n";
4527 e1.Element(name, oss.str());
4531 void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0)
4533 cmGlobalGenerator::TargetDependSet const& unordered =
4534 this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
4535 using OrderedTargetDependSet =
4536 cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
4537 OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
4538 Elem e1(e0, "ItemGroup");
4539 e1.SetHasElements();
4540 for (cmGeneratorTarget const* dt : depends) {
4541 if (!dt->IsInBuildSystem()) {
4544 // skip fortran targets as they can not be processed by MSBuild
4545 // the only reference will be in the .sln file
4546 if (this->GlobalGenerator->TargetIsFortranOnly(dt)) {
4549 cmLocalGenerator* lg = dt->GetLocalGenerator();
4550 std::string name = dt->GetName();
4552 if (cmValue p = dt->GetProperty("EXTERNAL_MSPROJECT")) {
4555 path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(),
4556 computeProjectFileExtension(dt));
4558 ConvertToWindowsSlash(path);
4559 Elem e2(e1, "ProjectReference");
4560 e2.Attribute("Include", path);
4561 e2.Element("Project", "{" + this->GlobalGenerator->GetGUID(name) + "}");
4562 e2.Element("Name", name);
4563 this->WriteDotNetReferenceCustomTags(e2, name);
4564 if (dt->IsCSharpOnly() || cmHasLiteralSuffix(path, "csproj")) {
4565 e2.Element("SkipGetTargetFrameworkProperties", "true");
4567 // Don't reference targets that don't produce any output.
4568 else if (this->Configurations.empty() ||
4569 dt->GetManagedType(this->Configurations[0]) ==
4570 cmGeneratorTarget::ManagedType::Undefined) {
4571 e2.Element("ReferenceOutputAssembly", "false");
4572 e2.Element("CopyToOutputDirectory", "Never");
4577 void cmVisualStudio10TargetGenerator::WritePlatformExtensions(Elem& e1)
4579 // This only applies to Windows 10 apps
4580 if (this->GlobalGenerator->TargetsWindowsStore() &&
4581 cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
4582 cmValue desktopExtensionsVersion =
4583 this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
4584 if (desktopExtensionsVersion) {
4585 this->WriteSinglePlatformExtension(e1, "WindowsDesktop",
4586 *desktopExtensionsVersion);
4588 cmValue mobileExtensionsVersion =
4589 this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
4590 if (mobileExtensionsVersion) {
4591 this->WriteSinglePlatformExtension(e1, "WindowsMobile",
4592 *mobileExtensionsVersion);
4597 void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
4598 Elem& e1, std::string const& extension, std::string const& version)
4600 const std::string s = "$([Microsoft.Build.Utilities.ToolLocationHelper]"
4601 "::GetPlatformExtensionSDKLocation(`" +
4602 extension + ", Version=" + version +
4603 "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
4604 "$(ExtensionSDKDirectoryRoot), null))"
4605 "\\DesignTime\\CommonConfiguration\\Neutral\\" +
4606 extension + ".props";
4608 Elem e2(e1, "Import");
4609 e2.Attribute("Project", s);
4610 e2.Attribute("Condition", "exists('" + s + "')");
4613 void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0)
4615 std::vector<std::string> sdkReferences;
4616 std::unique_ptr<Elem> spe1;
4617 if (cmValue vsSDKReferences =
4618 this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
4619 cmExpandList(*vsSDKReferences, sdkReferences);
4620 spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
4621 for (std::string const& ri : sdkReferences) {
4622 Elem(*spe1, "SDKReference").Attribute("Include", ri);
4626 // This only applies to Windows 10 apps
4627 if (this->GlobalGenerator->TargetsWindowsStore() &&
4628 cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
4629 cmValue desktopExtensionsVersion =
4630 this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
4631 cmValue mobileExtensionsVersion =
4632 this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
4633 cmValue iotExtensionsVersion =
4634 this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
4636 if (desktopExtensionsVersion || mobileExtensionsVersion ||
4637 iotExtensionsVersion) {
4639 spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
4641 if (desktopExtensionsVersion) {
4642 this->WriteSingleSDKReference(*spe1, "WindowsDesktop",
4643 *desktopExtensionsVersion);
4645 if (mobileExtensionsVersion) {
4646 this->WriteSingleSDKReference(*spe1, "WindowsMobile",
4647 *mobileExtensionsVersion);
4649 if (iotExtensionsVersion) {
4650 this->WriteSingleSDKReference(*spe1, "WindowsIoT",
4651 *iotExtensionsVersion);
4657 void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
4658 Elem& e1, std::string const& extension, std::string const& version)
4660 Elem(e1, "SDKReference")
4661 .Attribute("Include", extension + ", Version=" + version);
4664 void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile(
4667 if ((this->GlobalGenerator->TargetsWindowsStore() ||
4668 this->GlobalGenerator->TargetsWindowsPhone()) &&
4669 (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
4670 std::string pfxFile;
4671 for (cmGeneratorTarget::AllConfigSource const& source :
4672 this->GeneratorTarget->GetAllConfigSources()) {
4673 if (source.Kind == cmGeneratorTarget::SourceKindCertificate) {
4674 pfxFile = this->ConvertPath(source.Source->GetFullPath(), false);
4675 ConvertToWindowsSlash(pfxFile);
4680 if (this->IsMissingFiles &&
4681 !(this->GlobalGenerator->TargetsWindowsPhone() &&
4682 this->GlobalGenerator->GetSystemVersion() == "8.0")) {
4683 // Move the manifest to a project directory to avoid clashes
4684 std::string artifactDir =
4685 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
4686 ConvertToWindowsSlash(artifactDir);
4687 Elem e1(e0, "PropertyGroup");
4688 e1.Element("AppxPackageArtifactsDir", artifactDir + "\\");
4689 std::string resourcePriFile =
4690 this->DefaultArtifactDir + "/resources.pri";
4691 ConvertToWindowsSlash(resourcePriFile);
4692 e1.Element("ProjectPriFullPath", resourcePriFile);
4694 // If we are missing files and we don't have a certificate and
4695 // aren't targeting WP8.0, add a default certificate
4696 if (pfxFile.empty()) {
4697 std::string templateFolder =
4698 cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
4699 pfxFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
4700 cmSystemTools::CopyAFile(templateFolder + "/Windows_TemporaryKey.pfx",
4702 ConvertToWindowsSlash(pfxFile);
4703 this->AddedFiles.push_back(pfxFile);
4704 this->AddedDefaultCertificate = true;
4707 e1.Element("PackageCertificateKeyFile", pfxFile);
4708 std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile);
4709 if (!thumb.empty()) {
4710 e1.Element("PackageCertificateThumbprint", thumb);
4712 } else if (!pfxFile.empty()) {
4713 Elem e1(e0, "PropertyGroup");
4714 e1.Element("PackageCertificateKeyFile", pfxFile);
4715 std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile);
4716 if (!thumb.empty()) {
4717 e1.Element("PackageCertificateThumbprint", thumb);
4723 void cmVisualStudio10TargetGenerator::ClassifyAllConfigSources()
4725 for (cmGeneratorTarget::AllConfigSource const& source :
4726 this->GeneratorTarget->GetAllConfigSources()) {
4727 this->ClassifyAllConfigSource(source);
4731 void cmVisualStudio10TargetGenerator::ClassifyAllConfigSource(
4732 cmGeneratorTarget::AllConfigSource const& acs)
4735 case cmGeneratorTarget::SourceKindResx: {
4736 // Build and save the name of the corresponding .h file
4737 // This relationship will be used later when building the project files.
4738 // Both names would have been auto generated from Visual Studio
4739 // where the user supplied the file name and Visual Studio
4740 // appended the suffix.
4741 std::string resx = acs.Source->ResolveFullPath();
4742 std::string hFileName = resx.substr(0, resx.find_last_of('.')) + ".h";
4743 this->ExpectedResxHeaders.insert(hFileName);
4745 case cmGeneratorTarget::SourceKindXaml: {
4746 // Build and save the name of the corresponding .h and .cpp file
4747 // This relationship will be used later when building the project files.
4748 // Both names would have been auto generated from Visual Studio
4749 // where the user supplied the file name and Visual Studio
4750 // appended the suffix.
4751 std::string xaml = acs.Source->ResolveFullPath();
4752 std::string hFileName = xaml + ".h";
4753 std::string cppFileName = xaml + ".cpp";
4754 this->ExpectedXamlHeaders.insert(hFileName);
4755 this->ExpectedXamlSources.insert(cppFileName);
4762 bool cmVisualStudio10TargetGenerator::IsResxHeader(
4763 const std::string& headerFile)
4765 return this->ExpectedResxHeaders.count(headerFile) > 0;
4768 bool cmVisualStudio10TargetGenerator::IsXamlHeader(
4769 const std::string& headerFile)
4771 return this->ExpectedXamlHeaders.count(headerFile) > 0;
4774 bool cmVisualStudio10TargetGenerator::IsXamlSource(
4775 const std::string& sourceFile)
4777 return this->ExpectedXamlSources.count(sourceFile) > 0;
4780 void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1)
4782 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4783 bool isAppContainer = false;
4784 bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
4785 bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
4786 bool const isAndroid = this->GlobalGenerator->TargetsAndroid();
4787 std::string const& rev = this->GlobalGenerator->GetApplicationTypeRevision();
4788 if (isWindowsPhone || isWindowsStore) {
4789 e1.Element("ApplicationType",
4790 (isWindowsPhone ? "Windows Phone" : "Windows Store"));
4791 e1.Element("DefaultLanguage", "en-US");
4792 if (rev == "10.0") {
4793 e1.Element("ApplicationTypeRevision", rev);
4794 // Visual Studio 14.0 is necessary for building 10.0 apps
4795 e1.Element("MinimumVisualStudioVersion", "14.0");
4797 if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
4798 isAppContainer = true;
4800 } else if (rev == "8.1") {
4801 e1.Element("ApplicationTypeRevision", rev);
4802 // Visual Studio 12.0 is necessary for building 8.1 apps
4803 e1.Element("MinimumVisualStudioVersion", "12.0");
4805 if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
4806 isAppContainer = true;
4808 } else if (rev == "8.0") {
4809 e1.Element("ApplicationTypeRevision", rev);
4810 // Visual Studio 11.0 is necessary for building 8.0 apps
4811 e1.Element("MinimumVisualStudioVersion", "11.0");
4813 if (isWindowsStore &&
4814 this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
4815 isAppContainer = true;
4816 } else if (isWindowsPhone &&
4817 this->GeneratorTarget->GetType() ==
4818 cmStateEnums::EXECUTABLE) {
4819 e1.Element("XapOutputs", "true");
4820 e1.Element("XapFilename",
4821 this->Name + "_$(Configuration)_$(Platform).xap");
4824 } else if (isAndroid) {
4825 e1.Element("ApplicationType", "Android");
4826 e1.Element("ApplicationTypeRevision",
4827 gg->GetAndroidApplicationTypeRevision());
4829 if (isAppContainer) {
4830 e1.Element("AppContainerApplication", "true");
4831 } else if (!isAndroid) {
4832 if (this->Platform == "ARM64") {
4833 e1.Element("WindowsSDKDesktopARM64Support", "true");
4834 } else if (this->Platform == "ARM") {
4835 e1.Element("WindowsSDKDesktopARMSupport", "true");
4838 std::string const& targetPlatformVersion =
4839 gg->GetWindowsTargetPlatformVersion();
4840 if (!targetPlatformVersion.empty()) {
4841 e1.Element("WindowsTargetPlatformVersion", targetPlatformVersion);
4843 cmValue targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
4844 "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
4845 if (targetPlatformMinVersion) {
4846 e1.Element("WindowsTargetPlatformMinVersion", *targetPlatformMinVersion);
4847 } else if (isWindowsStore && rev == "10.0") {
4848 // If the min version is not set, then use the TargetPlatformVersion
4849 if (!targetPlatformVersion.empty()) {
4850 e1.Element("WindowsTargetPlatformMinVersion", targetPlatformVersion);
4854 // Added IoT Startup Task support
4855 if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
4856 e1.Element("ContainsStartupTask", "true");
4860 void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
4862 // For Windows and Windows Phone executables, we will assume that if a
4863 // manifest is not present that we need to add all the necessary files
4864 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4865 std::vector<cmGeneratorTarget::AllConfigSource> manifestSources =
4866 this->GeneratorTarget->GetAllConfigSources(
4867 cmGeneratorTarget::SourceKindAppManifest);
4868 std::string const& v = this->GlobalGenerator->GetSystemVersion();
4869 if (this->GlobalGenerator->TargetsWindowsPhone()) {
4871 // Look through the sources for WMAppManifest.xml
4872 bool foundManifest = false;
4873 for (cmGeneratorTarget::AllConfigSource const& source :
4874 this->GeneratorTarget->GetAllConfigSources()) {
4875 if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
4876 "wmappmanifest.xml" ==
4877 cmSystemTools::LowerCase(
4878 source.Source->GetLocation().GetName())) {
4879 foundManifest = true;
4883 if (!foundManifest) {
4884 this->IsMissingFiles = true;
4886 } else if (v == "8.1") {
4887 if (manifestSources.empty()) {
4888 this->IsMissingFiles = true;
4891 } else if (this->GlobalGenerator->TargetsWindowsStore()) {
4892 if (manifestSources.empty()) {
4894 this->IsMissingFiles = true;
4895 } else if (v == "8.1" || cmHasLiteralPrefix(v, "10.0")) {
4896 this->IsMissingFiles = true;
4903 void cmVisualStudio10TargetGenerator::WriteMissingFiles(Elem& e1)
4905 std::string const& v = this->GlobalGenerator->GetSystemVersion();
4906 if (this->GlobalGenerator->TargetsWindowsPhone()) {
4908 this->WriteMissingFilesWP80(e1);
4909 } else if (v == "8.1") {
4910 this->WriteMissingFilesWP81(e1);
4912 } else if (this->GlobalGenerator->TargetsWindowsStore()) {
4914 this->WriteMissingFilesWS80(e1);
4915 } else if (v == "8.1") {
4916 this->WriteMissingFilesWS81(e1);
4917 } else if (cmHasLiteralPrefix(v, "10.0")) {
4918 this->WriteMissingFilesWS10_0(e1);
4923 void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80(Elem& e1)
4925 std::string templateFolder =
4926 cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
4928 // For WP80, the manifest needs to be in the same folder as the project
4929 // this can cause an overwrite problem if projects aren't organized in
4931 std::string manifestFile =
4932 this->LocalGenerator->GetCurrentBinaryDirectory() + "/WMAppManifest.xml";
4933 std::string artifactDir =
4934 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
4935 ConvertToWindowsSlash(artifactDir);
4936 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
4937 std::string targetNameXML =
4938 cmVS10EscapeXML(this->GeneratorTarget->GetName());
4940 cmGeneratedFileStream fout(manifestFile);
4941 fout.SetCopyIfDifferent(true);
4943 /* clang-format off */
4945 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
4947 " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
4948 " AppPlatformVersion=\"8.0\">\n"
4949 "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
4950 "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
4951 " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
4952 " Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"CMake\""
4953 " Description=\"Default CMake App\" Publisher=\"CMake\""
4954 " PublisherID=\"{" << this->GUID << "}\">\n"
4955 "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
4956 << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
4957 "\t\t<Capabilities/>\n"
4959 "\t\t\t<DefaultTask Name=\"_default\""
4960 " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
4963 "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
4964 " TaskName=\"_default\">\n"
4965 "\t\t\t\t<TemplateFlip>\n"
4966 "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
4967 << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
4968 "\t\t\t\t\t<Count>0</Count>\n"
4969 "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
4970 << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
4971 "\t\t\t\t</TemplateFlip>\n"
4972 "\t\t\t</PrimaryToken>\n"
4974 "\t\t<ScreenResolutions>\n"
4975 "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
4976 "\t\t</ScreenResolutions>\n"
4979 /* clang-format on */
4981 std::string sourceFile = this->ConvertPath(manifestFile, false);
4982 ConvertToWindowsSlash(sourceFile);
4985 e2.Attribute("Include", sourceFile);
4986 e2.Element("SubType", "Designer");
4988 this->AddedFiles.push_back(sourceFile);
4990 std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
4991 cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png", smallLogo,
4993 ConvertToWindowsSlash(smallLogo);
4994 Elem(e1, "Image").Attribute("Include", smallLogo);
4995 this->AddedFiles.push_back(smallLogo);
4997 std::string logo = this->DefaultArtifactDir + "/Logo.png";
4998 cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false);
4999 ConvertToWindowsSlash(logo);
5000 Elem(e1, "Image").Attribute("Include", logo);
5001 this->AddedFiles.push_back(logo);
5003 std::string applicationIcon =
5004 this->DefaultArtifactDir + "/ApplicationIcon.png";
5005 cmSystemTools::CopyAFile(templateFolder + "/ApplicationIcon.png",
5006 applicationIcon, false);
5007 ConvertToWindowsSlash(applicationIcon);
5008 Elem(e1, "Image").Attribute("Include", applicationIcon);
5009 this->AddedFiles.push_back(applicationIcon);
5012 void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81(Elem& e1)
5014 std::string manifestFile =
5015 this->DefaultArtifactDir + "/package.appxManifest";
5016 std::string artifactDir =
5017 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5018 ConvertToWindowsSlash(artifactDir);
5019 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5020 std::string targetNameXML =
5021 cmVS10EscapeXML(this->GeneratorTarget->GetName());
5023 cmGeneratedFileStream fout(manifestFile);
5024 fout.SetCopyIfDifferent(true);
5026 /* clang-format off */
5028 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5029 "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
5030 " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
5031 " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
5032 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5033 " Version=\"1.0.0.0\" />\n"
5034 "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
5035 " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
5037 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5038 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5039 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5041 "\t<Prerequisites>\n"
5042 "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
5043 "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
5044 "\t</Prerequisites>\n"
5046 "\t\t<Resource Language=\"x-generate\" />\n"
5048 "\t<Applications>\n"
5049 "\t\t<Application Id=\"App\""
5050 " Executable=\"" << targetNameXML << ".exe\""
5051 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5052 "\t\t\t<m2:VisualElements\n"
5053 "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5054 "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5055 "\t\t\t\tBackgroundColor=\"#336699\"\n"
5056 "\t\t\t\tForegroundText=\"light\"\n"
5057 "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5058 "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5059 "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
5060 "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
5061 "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
5062 "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
5063 "\t\t\t\t</m2:DefaultTile>\n"
5064 "\t\t\t\t<m2:SplashScreen"
5065 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5066 "\t\t\t</m2:VisualElements>\n"
5067 "\t\t</Application>\n"
5068 "\t</Applications>\n"
5070 /* clang-format on */
5072 this->WriteCommonMissingFiles(e1, manifestFile);
5075 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80(Elem& e1)
5077 std::string manifestFile =
5078 this->DefaultArtifactDir + "/package.appxManifest";
5079 std::string artifactDir =
5080 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5081 ConvertToWindowsSlash(artifactDir);
5082 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5083 std::string targetNameXML =
5084 cmVS10EscapeXML(this->GeneratorTarget->GetName());
5086 cmGeneratedFileStream fout(manifestFile);
5087 fout.SetCopyIfDifferent(true);
5089 /* clang-format off */
5091 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5092 "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
5093 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5094 " Version=\"1.0.0.0\" />\n"
5096 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5097 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5098 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5100 "\t<Prerequisites>\n"
5101 "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
5102 "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
5103 "\t</Prerequisites>\n"
5105 "\t\t<Resource Language=\"x-generate\" />\n"
5107 "\t<Applications>\n"
5108 "\t\t<Application Id=\"App\""
5109 " Executable=\"" << targetNameXML << ".exe\""
5110 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5111 "\t\t\t<VisualElements"
5112 " DisplayName=\"" << targetNameXML << "\""
5113 " Description=\"" << targetNameXML << "\""
5114 " BackgroundColor=\"#336699\" ForegroundText=\"light\""
5115 " Logo=\"" << artifactDirXML << "\\Logo.png\""
5116 " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5117 "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
5118 " ShortName=\"" << targetNameXML << "\" />\n"
5119 "\t\t\t\t<SplashScreen"
5120 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5121 "\t\t\t</VisualElements>\n"
5122 "\t\t</Application>\n"
5123 "\t</Applications>\n"
5125 /* clang-format on */
5127 this->WriteCommonMissingFiles(e1, manifestFile);
5130 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81(Elem& e1)
5132 std::string manifestFile =
5133 this->DefaultArtifactDir + "/package.appxManifest";
5134 std::string artifactDir =
5135 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5136 ConvertToWindowsSlash(artifactDir);
5137 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5138 std::string targetNameXML =
5139 cmVS10EscapeXML(this->GeneratorTarget->GetName());
5141 cmGeneratedFileStream fout(manifestFile);
5142 fout.SetCopyIfDifferent(true);
5144 /* clang-format off */
5146 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5147 "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
5148 " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
5149 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5150 " Version=\"1.0.0.0\" />\n"
5152 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5153 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5154 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5156 "\t<Prerequisites>\n"
5157 "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
5158 "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
5159 "\t</Prerequisites>\n"
5161 "\t\t<Resource Language=\"x-generate\" />\n"
5163 "\t<Applications>\n"
5164 "\t\t<Application Id=\"App\""
5165 " Executable=\"" << targetNameXML << ".exe\""
5166 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5167 "\t\t\t<m2:VisualElements\n"
5168 "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5169 "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5170 "\t\t\t\tBackgroundColor=\"#336699\"\n"
5171 "\t\t\t\tForegroundText=\"light\"\n"
5172 "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5173 "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5174 "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
5175 "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
5176 "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
5177 "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
5178 "\t\t\t\t</m2:DefaultTile>\n"
5179 "\t\t\t\t<m2:SplashScreen"
5180 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5181 "\t\t\t</m2:VisualElements>\n"
5182 "\t\t</Application>\n"
5183 "\t</Applications>\n"
5185 /* clang-format on */
5187 this->WriteCommonMissingFiles(e1, manifestFile);
5190 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0(Elem& e1)
5192 std::string manifestFile =
5193 this->DefaultArtifactDir + "/package.appxManifest";
5194 std::string artifactDir =
5195 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5196 ConvertToWindowsSlash(artifactDir);
5197 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5198 std::string targetNameXML =
5199 cmVS10EscapeXML(this->GeneratorTarget->GetName());
5201 cmGeneratedFileStream fout(manifestFile);
5202 fout.SetCopyIfDifferent(true);
5204 /* clang-format off */
5206 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5208 "xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
5209 "\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
5210 "\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
5211 "\n\tIgnorableNamespaces=\"uap mp\">\n\n"
5212 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5213 " Version=\"1.0.0.0\" />\n"
5214 "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
5215 "\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
5217 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5218 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5219 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5221 "\t<Dependencies>\n"
5222 "\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
5223 "MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
5224 "\t</Dependencies>\n"
5227 "\t\t<Resource Language=\"x-generate\" />\n"
5229 "\t<Applications>\n"
5230 "\t\t<Application Id=\"App\""
5231 " Executable=\"" << targetNameXML << ".exe\""
5232 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5233 "\t\t\t<uap:VisualElements\n"
5234 "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5235 "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5236 "\t\t\t\tBackgroundColor=\"#336699\"\n"
5237 "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5238 "\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
5239 "\\SmallLogo44x44.png\">\n"
5240 "\t\t\t\t<uap:SplashScreen"
5241 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5242 "\t\t\t</uap:VisualElements>\n"
5243 "\t\t</Application>\n"
5244 "\t</Applications>\n"
5246 /* clang-format on */
5248 this->WriteCommonMissingFiles(e1, manifestFile);
5251 void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
5252 Elem& e1, const std::string& manifestFile)
5254 std::string templateFolder =
5255 cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
5257 std::string sourceFile = this->ConvertPath(manifestFile, false);
5258 ConvertToWindowsSlash(sourceFile);
5260 Elem e2(e1, "AppxManifest");
5261 e2.Attribute("Include", sourceFile);
5262 e2.Element("SubType", "Designer");
5264 this->AddedFiles.push_back(sourceFile);
5266 std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
5267 cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png", smallLogo,
5269 ConvertToWindowsSlash(smallLogo);
5270 Elem(e1, "Image").Attribute("Include", smallLogo);
5271 this->AddedFiles.push_back(smallLogo);
5273 std::string smallLogo44 = this->DefaultArtifactDir + "/SmallLogo44x44.png";
5274 cmSystemTools::CopyAFile(templateFolder + "/SmallLogo44x44.png", smallLogo44,
5276 ConvertToWindowsSlash(smallLogo44);
5277 Elem(e1, "Image").Attribute("Include", smallLogo44);
5278 this->AddedFiles.push_back(smallLogo44);
5280 std::string logo = this->DefaultArtifactDir + "/Logo.png";
5281 cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false);
5282 ConvertToWindowsSlash(logo);
5283 Elem(e1, "Image").Attribute("Include", logo);
5284 this->AddedFiles.push_back(logo);
5286 std::string storeLogo = this->DefaultArtifactDir + "/StoreLogo.png";
5287 cmSystemTools::CopyAFile(templateFolder + "/StoreLogo.png", storeLogo,
5289 ConvertToWindowsSlash(storeLogo);
5290 Elem(e1, "Image").Attribute("Include", storeLogo);
5291 this->AddedFiles.push_back(storeLogo);
5293 std::string splashScreen = this->DefaultArtifactDir + "/SplashScreen.png";
5294 cmSystemTools::CopyAFile(templateFolder + "/SplashScreen.png", splashScreen,
5296 ConvertToWindowsSlash(splashScreen);
5297 Elem(e1, "Image").Attribute("Include", splashScreen);
5298 this->AddedFiles.push_back(splashScreen);
5300 if (this->AddedDefaultCertificate) {
5301 // This file has already been added to the build so don't copy it
5302 std::string keyFile =
5303 this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
5304 ConvertToWindowsSlash(keyFile);
5305 Elem(e1, "None").Attribute("Include", keyFile);
5309 bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
5312 CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
5313 FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
5314 FILE_FLAG_BACKUP_SEMANTICS, 0);
5319 FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
5320 if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
5329 void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
5330 cmSourceFile const* sf, std::map<std::string, std::string>& tags)
5332 if (this->ProjectType == VsProjectType::csproj) {
5333 const cmPropertyMap& props = sf->GetProperties();
5334 for (const std::string& p : props.GetKeys()) {
5335 static const cm::string_view propNamePrefix = "VS_CSHARP_";
5336 if (cmHasPrefix(p, propNamePrefix)) {
5337 std::string tagName = p.substr(propNamePrefix.length());
5338 if (!tagName.empty()) {
5339 cmValue val = props.GetPropertyValue(p);
5340 if (cmNonempty(val)) {
5341 tags[tagName] = *val;
5343 tags.erase(tagName);
5351 void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
5352 Elem& e2, const std::map<std::string, std::string>& tags)
5354 for (const auto& i : tags) {
5355 e2.Element(i.first, i.second);
5359 std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
5360 cmSourceFile const* source)
5362 // For out of source files, we first check if a matching source group
5363 // for this file exists, otherwise we check if the path relative to current
5364 // source- or binary-dir is used within the link and return that.
5365 // In case of .cs files we can't do that automatically for files in the
5366 // binary directory, because this leads to compilation errors.
5368 std::string sourceGroupedFile;
5369 std::string const& fullFileName = source->GetFullPath();
5370 std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory();
5371 std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory();
5372 // unfortunately we have to copy the source groups, because
5373 // FindSourceGroup uses a regex which is modifying the group
5374 std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
5375 cmSourceGroup* sourceGroup =
5376 this->Makefile->FindSourceGroup(fullFileName, sourceGroups);
5377 if (sourceGroup && !sourceGroup->GetFullName().empty()) {
5378 sourceGroupedFile = sourceGroup->GetFullName() + "/" +
5379 cmsys::SystemTools::GetFilenameName(fullFileName);
5380 cmsys::SystemTools::ConvertToUnixSlashes(sourceGroupedFile);
5383 if (!sourceGroupedFile.empty() &&
5384 cmHasSuffix(fullFileName, sourceGroupedFile)) {
5385 link = sourceGroupedFile;
5386 } else if (cmHasPrefix(fullFileName, srcDir)) {
5387 link = fullFileName.substr(srcDir.length() + 1);
5388 } else if (!cmHasSuffix(fullFileName, ".cs") &&
5389 cmHasPrefix(fullFileName, binDir)) {
5390 link = fullFileName.substr(binDir.length() + 1);
5391 } else if (cmValue l = source->GetProperty("VS_CSHARP_Link")) {
5395 ConvertToWindowsSlash(link);
5399 std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
5400 const char* relativeFilePath) const
5402 // Always search in the standard modules location.
5404 cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath);
5405 ConvertToWindowsSlash(path);
5410 void cmVisualStudio10TargetGenerator::WriteStdOutEncodingUtf8(Elem& e1)
5412 if (this->GlobalGenerator->IsUtf8EncodingSupported()) {
5413 e1.Element("UseUtf8Encoding", "Always");
5414 } else if (this->GlobalGenerator->IsStdOutEncodingSupported()) {
5415 e1.Element("StdOutEncoding", "UTF-8");
5419 void cmVisualStudio10TargetGenerator::UpdateCache()
5421 std::vector<std::string> packageReferences;
5423 if (this->GeneratorTarget->HasPackageReferences()) {
5424 // Store a cache entry that later determines, if a package restore is
5426 this->GeneratorTarget->Makefile->AddCacheDefinition(
5427 this->GeneratorTarget->GetName() + "_REQUIRES_VS_PACKAGE_RESTORE", "ON",
5428 "Value Computed by CMake", cmStateEnums::STATIC);
5430 // If there are any dependencies that require package restore, inherit the
5432 cmGlobalGenerator::TargetDependSet const& unordered =
5433 this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
5434 using OrderedTargetDependSet =
5435 cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
5436 OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
5438 for (cmGeneratorTarget const* dt : depends) {
5439 if (dt->HasPackageReferences()) {
5440 this->GeneratorTarget->Makefile->AddCacheDefinition(
5441 this->GeneratorTarget->GetName() + "_REQUIRES_VS_PACKAGE_RESTORE",
5442 "ON", "Value Computed by CMake", cmStateEnums::STATIC);