CMake Nightly Date Stamp
[kiteware-cmake.git] / Source / cmVisualStudio10TargetGenerator.cxx
blob71a140b7db23ad1722113e8f1f31ad44ff894e96
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"
5 #include <algorithm>
6 #include <cstdio>
7 #include <cstring>
8 #include <iterator>
9 #include <set>
10 #include <sstream>
12 #include <cm/memory>
13 #include <cm/optional>
14 #include <cm/string_view>
15 #include <cm/vector>
16 #include <cmext/algorithm>
17 #include <cmext/string_view>
19 #include "windows.h"
20 // include wincrypt.h after windows.h
21 #include <wincrypt.h>
23 #include "cmsys/FStream.hxx"
24 #include "cmsys/RegularExpression.hxx"
26 #include "cmComputeLinkInformation.h"
27 #include "cmCryptoHash.h"
28 #include "cmCustomCommand.h"
29 #include "cmCustomCommandGenerator.h"
30 #include "cmFileSet.h"
31 #include "cmGeneratedFileStream.h"
32 #include "cmGeneratorExpression.h"
33 #include "cmGeneratorTarget.h"
34 #include "cmGlobalGenerator.h"
35 #include "cmGlobalVisualStudio10Generator.h"
36 #include "cmGlobalVisualStudio7Generator.h"
37 #include "cmGlobalVisualStudioGenerator.h"
38 #include "cmLinkLineDeviceComputer.h"
39 #include "cmList.h"
40 #include "cmListFileCache.h"
41 #include "cmLocalGenerator.h"
42 #include "cmLocalVisualStudio10Generator.h"
43 #include "cmLocalVisualStudio7Generator.h"
44 #include "cmLocalVisualStudioGenerator.h"
45 #include "cmMakefile.h"
46 #include "cmMessageType.h"
47 #include "cmPropertyMap.h"
48 #include "cmSourceFile.h"
49 #include "cmSourceFileLocation.h"
50 #include "cmSourceFileLocationKind.h"
51 #include "cmSourceGroup.h"
52 #include "cmStateTypes.h"
53 #include "cmStringAlgorithms.h"
54 #include "cmSystemTools.h"
55 #include "cmTarget.h"
56 #include "cmValue.h"
57 #include "cmVisualStudioGeneratorOptions.h"
59 struct cmIDEFlagTable;
61 static void ConvertToWindowsSlash(std::string& s);
63 static std::string cmVS10EscapeXML(std::string arg)
65 cmSystemTools::ReplaceString(arg, "&", "&amp;");
66 cmSystemTools::ReplaceString(arg, "<", "&lt;");
67 cmSystemTools::ReplaceString(arg, ">", "&gt;");
68 return arg;
71 static std::string cmVS10EscapeAttr(std::string arg)
73 cmSystemTools::ReplaceString(arg, "&", "&amp;");
74 cmSystemTools::ReplaceString(arg, "<", "&lt;");
75 cmSystemTools::ReplaceString(arg, ">", "&gt;");
76 cmSystemTools::ReplaceString(arg, "\"", "&quot;");
77 cmSystemTools::ReplaceString(arg, "\n", "&#10;");
78 return arg;
81 struct cmVisualStudio10TargetGenerator::Elem
83 std::ostream& S;
84 const int Indent;
85 bool HasElements = false;
86 bool HasContent = false;
87 std::string Tag;
89 Elem(std::ostream& s, std::string tag)
90 : S(s)
91 , Indent(0)
92 , Tag(std::move(tag))
94 this->StartElement();
96 Elem(const Elem&) = delete;
97 Elem(Elem& par, cm::string_view tag)
98 : S(par.S)
99 , Indent(par.Indent + 1)
100 , Tag(std::string(tag))
102 par.SetHasElements();
103 this->StartElement();
105 void SetHasElements()
107 if (!HasElements) {
108 this->S << '>';
109 HasElements = true;
112 std::ostream& WriteString(const char* line);
113 void StartElement() { this->WriteString("<") << this->Tag; }
114 void Element(cm::string_view tag, std::string val)
116 Elem(*this, tag).Content(std::move(val));
118 Elem& Attribute(const char* an, std::string av)
120 this->S << ' ' << an << "=\"" << cmVS10EscapeAttr(std::move(av)) << '"';
121 return *this;
123 void Content(std::string val)
125 if (!this->HasContent) {
126 this->S << '>';
127 this->HasContent = true;
129 this->S << cmVS10EscapeXML(std::move(val));
131 ~Elem()
133 // Do not emit element which has not been started
134 if (Tag.empty()) {
135 return;
138 if (HasElements) {
139 this->WriteString("</") << this->Tag << '>';
140 } else if (HasContent) {
141 this->S << "</" << this->Tag << '>';
142 } else {
143 this->S << " />";
147 void WritePlatformConfigTag(const std::string& tag, const std::string& cond,
148 const std::string& content);
151 class cmVS10GeneratorOptions : public cmVisualStudioGeneratorOptions
153 public:
154 using Elem = cmVisualStudio10TargetGenerator::Elem;
155 cmVS10GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool,
156 cmVS7FlagTable const* table,
157 cmVisualStudio10TargetGenerator* g = nullptr)
158 : cmVisualStudioGeneratorOptions(lg, tool, table)
159 , TargetGenerator(g)
163 void OutputFlag(std::ostream& /*fout*/, int /*indent*/,
164 const std::string& tag, const std::string& content) override
166 if (!this->GetConfiguration().empty()) {
167 // if there are configuration specific flags, then
168 // use the configuration specific tag for PreprocessorDefinitions
169 const std::string cond =
170 this->TargetGenerator->CalcCondition(this->GetConfiguration());
171 this->Parent->WritePlatformConfigTag(tag, cond, content);
172 } else {
173 this->Parent->Element(tag, content);
177 private:
178 cmVisualStudio10TargetGenerator* const TargetGenerator;
179 Elem* Parent = nullptr;
180 friend cmVisualStudio10TargetGenerator::OptionsHelper;
183 struct cmVisualStudio10TargetGenerator::OptionsHelper
185 cmVS10GeneratorOptions& O;
186 OptionsHelper(cmVS10GeneratorOptions& o, Elem& e)
187 : O(o)
189 O.Parent = &e;
191 ~OptionsHelper() { O.Parent = nullptr; }
193 void OutputPreprocessorDefinitions(const std::string& lang)
195 O.OutputPreprocessorDefinitions(O.Parent->S, O.Parent->Indent + 1, lang);
197 void OutputAdditionalIncludeDirectories(const std::string& lang)
199 O.OutputAdditionalIncludeDirectories(O.Parent->S, O.Parent->Indent + 1,
200 lang);
202 void OutputFlagMap() { O.OutputFlagMap(O.Parent->S, O.Parent->Indent + 1); }
203 void PrependInheritedString(std::string const& key)
205 O.PrependInheritedString(key);
209 static std::string cmVS10EscapeComment(std::string const& comment)
211 // MSBuild takes the CDATA of a <Message></Message> element and just
212 // does "echo $CDATA" with no escapes. We must encode the string.
213 // http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx
214 std::string echoable;
215 for (char c : comment) {
216 switch (c) {
217 case '\r':
218 break;
219 case '\n':
220 echoable += '\t';
221 break;
222 case '"': /* no break */
223 case '|': /* no break */
224 case '&': /* no break */
225 case '<': /* no break */
226 case '>': /* no break */
227 case '^':
228 echoable += '^'; /* no break */
229 CM_FALLTHROUGH;
230 default:
231 echoable += c;
232 break;
235 return echoable;
238 static bool cmVS10IsTargetsFile(std::string const& path)
240 std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
241 return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
244 static VsProjectType computeProjectType(cmGeneratorTarget const* t)
246 if (t->IsCSharpOnly()) {
247 return VsProjectType::csproj;
249 return VsProjectType::vcxproj;
252 static std::string computeProjectFileExtension(VsProjectType projectType)
254 switch (projectType) {
255 case VsProjectType::csproj:
256 return ".csproj";
257 case VsProjectType::proj:
258 return ".proj";
259 default:
260 return ".vcxproj";
264 static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
266 return computeProjectFileExtension(computeProjectType(t));
269 cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
270 cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
271 : GeneratorTarget(target)
272 , Makefile(target->Target->GetMakefile())
273 , Platform(gg->GetPlatformName())
274 , Name(target->GetName())
275 , GUID(gg->GetGUID(this->Name))
276 , GlobalGenerator(gg)
277 , LocalGenerator(
278 (cmLocalVisualStudio10Generator*)target->GetLocalGenerator())
280 this->Configurations =
281 this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
282 this->NsightTegra = gg->IsNsightTegra();
283 this->Android = gg->TargetsAndroid();
284 auto scanProp = target->GetProperty("CXX_SCAN_FOR_MODULES");
285 for (auto const& config : this->Configurations) {
286 if (scanProp.IsSet()) {
287 this->ScanSourceForModuleDependencies[config] = scanProp.IsOn();
288 } else {
289 this->ScanSourceForModuleDependencies[config] =
290 target->NeedCxxDyndep(config) ==
291 cmGeneratorTarget::CxxModuleSupport::Enabled;
294 for (unsigned int& version : this->NsightTegraVersion) {
295 version = 0;
297 sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
298 &this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
299 &this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
300 this->MSTools = !this->NsightTegra && !this->Android;
301 this->Managed = false;
302 this->TargetCompileAsWinRT = false;
303 this->IsMissingFiles = false;
304 this->DefaultArtifactDir =
305 cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
306 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
307 this->InSourceBuild = (this->Makefile->GetCurrentSourceDirectory() ==
308 this->Makefile->GetCurrentBinaryDirectory());
309 this->ClassifyAllConfigSources();
312 cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator() = default;
314 std::string cmVisualStudio10TargetGenerator::CalcCondition(
315 const std::string& config) const
317 std::ostringstream oss;
318 oss << "'$(Configuration)|$(Platform)'=='" << config << '|' << this->Platform
319 << '\'';
320 // handle special case for 32 bit C# targets
321 if (this->ProjectType == VsProjectType::csproj &&
322 this->Platform == "Win32"_s) {
323 oss << " Or "
324 "'$(Configuration)|$(Platform)'=='"
325 << config
326 << "|x86"
327 "'";
329 return oss.str();
332 void cmVisualStudio10TargetGenerator::Elem::WritePlatformConfigTag(
333 const std::string& tag, const std::string& cond, const std::string& content)
335 Elem(*this, tag).Attribute("Condition", cond).Content(content);
338 std::ostream& cmVisualStudio10TargetGenerator::Elem::WriteString(
339 const char* line)
341 this->S << '\n';
342 this->S.fill(' ');
343 this->S.width(this->Indent * 2);
344 // write an empty string to get the fill level indent to print
345 this->S << "";
346 this->S << line;
347 return this->S;
350 #define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
351 #define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
352 #define VS10_CXX_USER_PROPS \
353 "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
354 #define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
356 #define VS10_CSharp_DEFAULT_PROPS \
357 "$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
358 // This does not seem to exist by default, it's just provided for consistency
359 // in case users want to have default custom props for C# targets
360 #define VS10_CSharp_USER_PROPS \
361 "$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
362 #define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
364 #define VS10_CSharp_NETCF_TARGETS \
365 "$(MSBuildExtensionsPath)\\Microsoft\\$(TargetFrameworkIdentifier)\\" \
366 "$(TargetFrameworkTargetsVersion)\\Microsoft.$(TargetFrameworkIdentifier)" \
367 ".CSharp.targets"
369 void cmVisualStudio10TargetGenerator::Generate()
371 if (this->GeneratorTarget->IsSynthetic()) {
372 this->GeneratorTarget->Makefile->IssueMessage(
373 MessageType::FATAL_ERROR,
374 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
375 "\" contains C++ modules intended for BMI-only compilation. "
376 "This is not yet supported by the Visual Studio generator."));
377 return;
380 for (std::string const& config : this->Configurations) {
381 this->GeneratorTarget->CheckCxxModuleStatus(config);
384 this->ProjectType = computeProjectType(this->GeneratorTarget);
385 this->Managed = this->ProjectType == VsProjectType::csproj;
386 const std::string ProjectFileExtension =
387 computeProjectFileExtension(this->ProjectType);
389 if (this->ProjectType == VsProjectType::csproj &&
390 this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
391 std::string message =
392 cmStrCat("The C# target \"", this->GeneratorTarget->GetName(),
393 "\" is of type STATIC_LIBRARY. This is discouraged (and may be "
394 "disabled in future). Make it a SHARED library instead.");
395 this->Makefile->IssueMessage(MessageType::DEPRECATION_WARNING, message);
398 if (this->Android &&
399 this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE &&
400 !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
401 this->GlobalGenerator->AddAndroidExecutableWarning(this->Name);
404 // Tell the global generator the name of the project file
405 this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
406 this->Name);
407 this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
408 ProjectFileExtension);
409 this->DotNetHintReferences.clear();
410 this->AdditionalUsingDirectories.clear();
411 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
412 if (!this->ComputeClOptions()) {
413 return;
415 if (!this->ComputeRcOptions()) {
416 return;
418 if (!this->ComputeCudaOptions()) {
419 return;
421 if (!this->ComputeCudaLinkOptions()) {
422 return;
424 if (!this->ComputeMarmasmOptions()) {
425 return;
427 if (!this->ComputeMasmOptions()) {
428 return;
430 if (!this->ComputeNasmOptions()) {
431 return;
433 if (!this->ComputeLinkOptions()) {
434 return;
436 if (!this->ComputeLibOptions()) {
437 return;
440 std::string path =
441 cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
442 this->Name, ProjectFileExtension);
443 cmGeneratedFileStream BuildFileStream(path);
444 const std::string& PathToProjectFile = path;
445 BuildFileStream.SetCopyIfDifferent(true);
447 // Write the encoding header into the file
448 char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
449 BuildFileStream.write(magic, 3);
451 if (this->ProjectType == VsProjectType::csproj &&
452 this->GeneratorTarget->IsDotNetSdkTarget() &&
453 this->GlobalGenerator->GetVersion() >=
454 cmGlobalVisualStudioGenerator::VSVersion::VS16) {
455 this->WriteSdkStyleProjectFile(BuildFileStream);
456 } else {
457 this->WriteClassicMsBuildProjectFile(BuildFileStream);
460 if (BuildFileStream.Close()) {
461 this->GlobalGenerator->FileReplacedDuringGenerate(PathToProjectFile);
464 // The groups are stored in a separate file for VS 10
465 this->WriteGroups();
467 // Update cache with project-specific entries.
468 this->UpdateCache();
471 void cmVisualStudio10TargetGenerator::WriteClassicMsBuildProjectFile(
472 cmGeneratedFileStream& BuildFileStream)
474 BuildFileStream << R"(<?xml version="1.0" encoding=")"
475 << this->GlobalGenerator->Encoding() << "\"?>";
477 Elem e0(BuildFileStream, "Project");
478 e0.Attribute("DefaultTargets", "Build");
479 const char* toolsVersion = this->GlobalGenerator->GetToolsVersion();
480 e0.Attribute("ToolsVersion", toolsVersion);
481 e0.Attribute("xmlns",
482 "http://schemas.microsoft.com/developer/msbuild/2003");
484 if (this->NsightTegra) {
485 Elem e1(e0, "PropertyGroup");
486 e1.Attribute("Label", "NsightTegraProject");
487 const unsigned int nsightTegraMajorVersion = this->NsightTegraVersion[0];
488 const unsigned int nsightTegraMinorVersion = this->NsightTegraVersion[1];
489 if (nsightTegraMajorVersion >= 2) {
490 if (nsightTegraMajorVersion > 3 ||
491 (nsightTegraMajorVersion == 3 && nsightTegraMinorVersion >= 1)) {
492 e1.Element("NsightTegraProjectRevisionNumber", "11");
493 } else {
494 // Nsight Tegra 2.0 uses project revision 9.
495 e1.Element("NsightTegraProjectRevisionNumber", "9");
497 // Tell newer versions to upgrade silently when loading.
498 e1.Element("NsightTegraUpgradeOnceWithoutPrompt", "true");
499 } else {
500 // Require Nsight Tegra 1.6 for JCompile support.
501 e1.Element("NsightTegraProjectRevisionNumber", "7");
505 if (const char* hostArch =
506 this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
507 Elem e1(e0, "PropertyGroup");
508 e1.Element("PreferredToolArchitecture", hostArch);
511 // The ALL_BUILD, PACKAGE, and ZERO_CHECK projects transitively include
512 // Microsoft.Common.CurrentVersion.targets which triggers Target
513 // ResolveNugetPackageAssets when SDK-style targets are in the project.
514 // However, these projects have no nuget packages to reference and the
515 // build fails.
516 // Setting ResolveNugetPackages to false skips this target and the build
517 // succeeds.
518 cm::string_view targetName{ this->GeneratorTarget->GetName() };
519 if (targetName == "ALL_BUILD"_s || targetName == "PACKAGE"_s ||
520 targetName == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
521 Elem e1(e0, "PropertyGroup");
522 e1.Element("ResolveNugetPackages", "false");
525 if (this->ProjectType != VsProjectType::csproj) {
526 this->WriteProjectConfigurations(e0);
530 Elem e1(e0, "PropertyGroup");
531 this->WriteCommonPropertyGroupGlobals(e1);
533 if ((this->MSTools || this->Android) &&
534 this->GeneratorTarget->IsInBuildSystem()) {
535 this->WriteApplicationTypeSettings(e1);
536 this->VerifyNecessaryFiles();
539 cmValue vsProjectName =
540 this->GeneratorTarget->GetProperty("VS_SCC_PROJECTNAME");
541 cmValue vsLocalPath =
542 this->GeneratorTarget->GetProperty("VS_SCC_LOCALPATH");
543 cmValue vsProvider =
544 this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER");
546 if (vsProjectName && vsLocalPath && vsProvider) {
547 e1.Element("SccProjectName", *vsProjectName);
548 e1.Element("SccLocalPath", *vsLocalPath);
549 e1.Element("SccProvider", *vsProvider);
551 cmValue vsAuxPath =
552 this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH");
553 if (vsAuxPath) {
554 e1.Element("SccAuxPath", *vsAuxPath);
558 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
559 e1.Element("WinMDAssembly", "true");
562 e1.Element("Platform", this->Platform);
563 cmValue projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL");
564 e1.Element("ProjectName", projLabel ? *projLabel : this->Name);
566 cm::optional<std::string> targetFramework;
567 cm::optional<std::string> targetFrameworkVersion;
568 cm::optional<std::string> targetFrameworkIdentifier;
569 cm::optional<std::string> targetFrameworkTargetsVersion;
570 if (cmValue tf =
571 this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK")) {
572 targetFramework = *tf;
573 } else if (cmValue vstfVer = this->GeneratorTarget->GetProperty(
574 "VS_DOTNET_TARGET_FRAMEWORK_VERSION")) {
575 // FIXME: Someday, add a deprecation warning for VS_* property.
576 targetFrameworkVersion = *vstfVer;
577 } else if (cmValue tfVer = this->GeneratorTarget->GetProperty(
578 "DOTNET_TARGET_FRAMEWORK_VERSION")) {
579 targetFrameworkVersion = *tfVer;
580 } else if (this->ProjectType == VsProjectType::csproj) {
581 targetFrameworkVersion =
582 this->GlobalGenerator->GetTargetFrameworkVersion();
584 if (this->ProjectType == VsProjectType::vcxproj &&
585 this->GlobalGenerator->TargetsWindowsCE()) {
586 e1.Element("EnableRedirectPlatform", "true");
587 e1.Element("RedirectPlatformValue", this->Platform);
589 if (this->ProjectType == VsProjectType::csproj) {
590 if (this->GlobalGenerator->TargetsWindowsCE()) {
591 // FIXME: These target VS_TARGET_FRAMEWORK* target properties
592 // are undocumented settings only ever supported for WinCE.
593 // We need a better way to control these in general.
594 if (cmValue tfId = this->GeneratorTarget->GetProperty(
595 "VS_TARGET_FRAMEWORK_IDENTIFIER")) {
596 targetFrameworkIdentifier = *tfId;
598 if (cmValue tfTargetsVer = this->GeneratorTarget->GetProperty(
599 "VS_TARGET_FRAMEWORKS_TARGET_VERSION")) {
600 targetFrameworkTargetsVersion = *tfTargetsVer;
603 if (!targetFrameworkIdentifier) {
604 targetFrameworkIdentifier =
605 this->GlobalGenerator->GetTargetFrameworkIdentifier();
607 if (!targetFrameworkTargetsVersion) {
608 targetFrameworkTargetsVersion =
609 this->GlobalGenerator->GetTargetFrameworkTargetsVersion();
612 if (targetFramework) {
613 if (targetFramework->find(';') != std::string::npos) {
614 e1.Element("TargetFrameworks", *targetFramework);
615 } else {
616 e1.Element("TargetFramework", *targetFramework);
619 if (targetFrameworkVersion) {
620 e1.Element("TargetFrameworkVersion", *targetFrameworkVersion);
622 if (targetFrameworkIdentifier) {
623 e1.Element("TargetFrameworkIdentifier", *targetFrameworkIdentifier);
625 if (targetFrameworkTargetsVersion) {
626 e1.Element("TargetFrameworkTargetsVersion",
627 *targetFrameworkTargetsVersion);
629 if (!this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString()
630 .empty()) {
631 e1.Element(
632 "CudaToolkitCustomDir",
633 cmStrCat(
634 this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString(),
635 this->GlobalGenerator
636 ->GetPlatformToolsetCudaNvccSubdirString()));
640 // Disable the project upgrade prompt that is displayed the first time a
641 // project using an older toolset version is opened in a newer version of
642 // the IDE.
643 e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
645 if (const char* vcTargetsPath =
646 this->GlobalGenerator->GetCustomVCTargetsPath()) {
647 e1.Element("VCTargetsPath", vcTargetsPath);
650 if (this->Managed) {
651 if (this->LocalGenerator->GetVersion() >=
652 cmGlobalVisualStudioGenerator::VSVersion::VS17) {
653 e1.Element("ManagedAssembly", "true");
655 std::string outputType;
656 switch (this->GeneratorTarget->GetType()) {
657 case cmStateEnums::OBJECT_LIBRARY:
658 case cmStateEnums::STATIC_LIBRARY:
659 case cmStateEnums::SHARED_LIBRARY:
660 outputType = "Library";
661 break;
662 case cmStateEnums::MODULE_LIBRARY:
663 outputType = "Module";
664 break;
665 case cmStateEnums::EXECUTABLE: {
666 auto const win32 =
667 this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
668 if (win32.find("$<") != std::string::npos) {
669 this->Makefile->IssueMessage(
670 MessageType::FATAL_ERROR,
671 cmStrCat(
672 "Target \"", this->GeneratorTarget->GetName(),
673 "\" has a generator expression in its WIN32_EXECUTABLE "
674 "property. This is not supported on managed executables."));
675 return;
677 if (cmIsOn(win32)) {
678 outputType = "WinExe";
679 } else {
680 outputType = "Exe";
682 } break;
683 case cmStateEnums::UTILITY:
684 case cmStateEnums::INTERFACE_LIBRARY:
685 case cmStateEnums::GLOBAL_TARGET:
686 outputType = "Utility";
687 break;
688 case cmStateEnums::UNKNOWN_LIBRARY:
689 break;
691 e1.Element("OutputType", outputType);
692 e1.Element("AppDesignerFolder", "Properties");
696 cmValue startupObject =
697 this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
699 if (startupObject && this->Managed) {
700 Elem e1(e0, "PropertyGroup");
701 e1.Element("StartupObject", *startupObject);
704 switch (this->ProjectType) {
705 case VsProjectType::vcxproj: {
706 Elem(e0, "Import").Attribute("Project", VS10_CXX_DEFAULT_PROPS);
707 std::string const& props =
708 this->GlobalGenerator->GetPlatformToolsetVersionProps();
709 if (!props.empty()) {
710 Elem(e0, "Import").Attribute("Project", props);
712 } break;
713 case VsProjectType::csproj:
714 Elem(e0, "Import")
715 .Attribute("Project", VS10_CSharp_DEFAULT_PROPS)
716 .Attribute("Condition", "Exists('" VS10_CSharp_DEFAULT_PROPS "')");
717 break;
718 default:
719 break;
722 this->WriteProjectConfigurationValues(e0);
724 if (this->ProjectType == VsProjectType::vcxproj) {
725 Elem(e0, "Import").Attribute("Project", VS10_CXX_PROPS);
728 Elem e1(e0, "ImportGroup");
729 e1.Attribute("Label", "ExtensionSettings");
730 e1.SetHasElements();
732 if (this->GlobalGenerator->IsCudaEnabled()) {
733 auto customDir =
734 this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
735 std::string cudaPath = customDir.empty()
736 ? "$(VCTargetsPath)\\BuildCustomizations\\"
737 : cmStrCat(customDir,
738 this->GlobalGenerator
739 ->GetPlatformToolsetCudaVSIntegrationSubdirString(),
740 R"(extras\visual_studio_integration\MSBuildExtensions\)");
741 Elem(e1, "Import")
742 .Attribute("Project",
743 cmStrCat(std::move(cudaPath), "CUDA ",
744 this->GlobalGenerator->GetPlatformToolsetCuda(),
745 ".props"));
747 if (this->GlobalGenerator->IsMarmasmEnabled()) {
748 Elem(e1, "Import")
749 .Attribute("Project",
750 "$(VCTargetsPath)\\BuildCustomizations\\marmasm.props");
752 if (this->GlobalGenerator->IsMasmEnabled()) {
753 Elem(e1, "Import")
754 .Attribute("Project",
755 "$(VCTargetsPath)\\BuildCustomizations\\masm.props");
757 if (this->GlobalGenerator->IsNasmEnabled()) {
758 // Always search in the standard modules location.
759 std::string propsTemplate =
760 GetCMakeFilePath("Templates/MSBuild/nasm.props.in");
762 std::string propsLocal =
763 cmStrCat(this->DefaultArtifactDir, "\\nasm.props");
764 ConvertToWindowsSlash(propsLocal);
765 this->Makefile->ConfigureFile(propsTemplate, propsLocal, false, true,
766 true);
767 Elem(e1, "Import").Attribute("Project", propsLocal);
771 Elem e1(e0, "ImportGroup");
772 e1.Attribute("Label", "PropertySheets");
773 std::string props;
774 switch (this->ProjectType) {
775 case VsProjectType::vcxproj:
776 props = VS10_CXX_USER_PROPS;
777 break;
778 case VsProjectType::csproj:
779 props = VS10_CSharp_USER_PROPS;
780 break;
781 default:
782 break;
784 if (cmValue p = this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
785 props = *p;
787 if (!props.empty()) {
788 ConvertToWindowsSlash(props);
789 Elem(e1, "Import")
790 .Attribute("Project", props)
791 .Attribute("Condition", cmStrCat("exists('", props, "')"))
792 .Attribute("Label", "LocalAppDataPlatform");
795 this->WritePlatformExtensions(e1);
798 this->WriteDotNetDocumentationFile(e0);
799 Elem(e0, "PropertyGroup").Attribute("Label", "UserMacros");
800 this->WriteWinRTPackageCertificateKeyFile(e0);
801 this->WritePathAndIncrementalLinkOptions(e0);
802 this->WritePublicProjectContentOptions(e0);
803 this->WriteCEDebugProjectConfigurationValues(e0);
804 this->WriteItemDefinitionGroups(e0);
805 this->WriteCustomCommands(e0);
806 this->WriteAllSources(e0);
807 this->WriteDotNetReferences(e0);
808 this->WriteFrameworkReferences(e0);
809 this->WritePackageReferences(e0);
810 this->WriteImports(e0);
811 this->WriteEmbeddedResourceGroup(e0);
812 this->WriteXamlFilesGroup(e0);
813 this->WriteWinRTReferences(e0);
814 this->WriteProjectReferences(e0);
815 this->WriteSDKReferences(e0);
816 switch (this->ProjectType) {
817 case VsProjectType::vcxproj:
818 Elem(e0, "Import").Attribute("Project", VS10_CXX_TARGETS);
819 break;
820 case VsProjectType::csproj:
821 if (this->GlobalGenerator->TargetsWindowsCE()) {
822 Elem(e0, "Import").Attribute("Project", VS10_CSharp_NETCF_TARGETS);
823 } else {
824 Elem(e0, "Import").Attribute("Project", VS10_CSharp_TARGETS);
826 break;
827 default:
828 break;
831 this->WriteTargetSpecificReferences(e0);
833 Elem e1(e0, "ImportGroup");
834 e1.Attribute("Label", "ExtensionTargets");
835 e1.SetHasElements();
836 this->WriteTargetsFileReferences(e1);
837 if (this->GlobalGenerator->IsCudaEnabled()) {
838 auto customDir =
839 this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
840 std::string cudaPath = customDir.empty()
841 ? "$(VCTargetsPath)\\BuildCustomizations\\"
842 : cmStrCat(customDir,
843 this->GlobalGenerator
844 ->GetPlatformToolsetCudaVSIntegrationSubdirString(),
845 R"(extras\visual_studio_integration\MSBuildExtensions\)");
846 Elem(e1, "Import")
847 .Attribute("Project",
848 cmStrCat(std::move(cudaPath), "CUDA ",
849 this->GlobalGenerator->GetPlatformToolsetCuda(),
850 ".targets"));
852 if (this->GlobalGenerator->IsMarmasmEnabled()) {
853 Elem(e1, "Import")
854 .Attribute("Project",
855 "$(VCTargetsPath)\\BuildCustomizations\\marmasm.targets");
857 if (this->GlobalGenerator->IsMasmEnabled()) {
858 Elem(e1, "Import")
859 .Attribute("Project",
860 "$(VCTargetsPath)\\BuildCustomizations\\masm.targets");
862 if (this->GlobalGenerator->IsNasmEnabled()) {
863 std::string nasmTargets =
864 GetCMakeFilePath("Templates/MSBuild/nasm.targets");
865 Elem(e1, "Import").Attribute("Project", nasmTargets);
868 if (this->ProjectType == VsProjectType::vcxproj &&
869 this->HaveCustomCommandDepfile) {
870 std::string depfileTargets =
871 GetCMakeFilePath("Templates/MSBuild/CustomBuildDepFile.targets");
872 Elem(e0, "Import").Attribute("Project", depfileTargets);
874 if (this->ProjectType == VsProjectType::csproj) {
875 for (std::string const& c : this->Configurations) {
876 Elem e1(e0, "PropertyGroup");
877 e1.Attribute("Condition",
878 cmStrCat("'$(Configuration)' == '", c, '\''));
879 e1.SetHasElements();
880 this->WriteEvents(e1, c);
882 // make sure custom commands are executed before build (if necessary)
884 Elem e1(e0, "PropertyGroup");
885 std::ostringstream oss;
886 oss << "\n";
887 for (std::string const& i : this->CSharpCustomCommandNames) {
888 oss << " " << i << ";\n";
890 oss << " "
891 "$(BuildDependsOn)\n";
892 e1.Element("BuildDependsOn", oss.str());
898 void cmVisualStudio10TargetGenerator::WriteSdkStyleProjectFile(
899 cmGeneratedFileStream& BuildFileStream)
901 if (this->ProjectType != VsProjectType::csproj ||
902 !this->GeneratorTarget->IsDotNetSdkTarget()) {
903 std::string message =
904 cmStrCat("The target \"", this->GeneratorTarget->GetName(),
905 "\" is not eligible for .Net SDK style project.");
906 this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
907 return;
910 Elem e0(BuildFileStream, "Project");
911 e0.Attribute("Sdk", *this->GeneratorTarget->GetProperty("DOTNET_SDK"));
914 Elem e1(e0, "PropertyGroup");
915 this->WriteCommonPropertyGroupGlobals(e1);
917 e1.Element("EnableDefaultItems", "false");
918 // Disable the project upgrade prompt that is displayed the first time a
919 // project using an older toolset version is opened in a newer version
920 // of the IDE.
921 e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
922 e1.Element("ManagedAssembly", "true");
924 cmValue targetFramework =
925 this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK");
926 if (targetFramework) {
927 if (targetFramework->find(';') != std::string::npos) {
928 e1.Element("TargetFrameworks", *targetFramework);
929 } else {
930 e1.Element("TargetFramework", *targetFramework);
931 e1.Element("AppendTargetFrameworkToOutputPath", "false");
933 } else {
934 e1.Element("TargetFramework", "net5.0");
935 e1.Element("AppendTargetFrameworkToOutputPath", "false");
938 std::string outputType;
939 switch (this->GeneratorTarget->GetType()) {
940 case cmStateEnums::OBJECT_LIBRARY:
941 case cmStateEnums::STATIC_LIBRARY:
942 case cmStateEnums::MODULE_LIBRARY:
943 this->Makefile->IssueMessage(
944 MessageType::FATAL_ERROR,
945 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
946 "\" is of a type not supported for managed binaries."));
947 return;
948 case cmStateEnums::SHARED_LIBRARY:
949 outputType = "Library";
950 break;
951 case cmStateEnums::EXECUTABLE: {
952 auto const win32 =
953 this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
954 if (win32.find("$<") != std::string::npos) {
955 this->Makefile->IssueMessage(
956 MessageType::FATAL_ERROR,
957 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
958 "\" has a generator expression in its WIN32_EXECUTABLE "
959 "property. This is not supported on managed "
960 "executables."));
961 return;
963 if (cmIsOn(win32)) {
964 outputType = "WinExe";
965 } else {
966 outputType = "Exe";
968 } break;
969 case cmStateEnums::UTILITY:
970 case cmStateEnums::INTERFACE_LIBRARY:
971 case cmStateEnums::GLOBAL_TARGET:
972 outputType = "Utility";
973 break;
974 case cmStateEnums::UNKNOWN_LIBRARY:
975 break;
977 e1.Element("OutputType", outputType);
979 cmValue startupObject =
980 this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
981 if (startupObject) {
982 e1.Element("StartupObject", *startupObject);
986 for (const std::string& config : this->Configurations) {
987 Elem e1(e0, "PropertyGroup");
988 e1.Attribute("Condition",
989 cmStrCat("'$(Configuration)' == '", config, '\''));
990 e1.SetHasElements();
992 std::string outDir =
993 cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
994 ConvertToWindowsSlash(outDir);
995 e1.Element("OutputPath", outDir);
997 e1.Element("AssemblyName", GetAssemblyName(config));
999 Options& o = *(this->ClOptions[config]);
1000 OptionsHelper oh(o, e1);
1001 oh.OutputFlagMap();
1004 for (const std::string& config : this->Configurations) {
1005 this->WriteSdkStyleEvents(e0, config);
1008 this->WriteDotNetDocumentationFile(e0);
1009 this->WriteCustomCommands(e0);
1010 this->WriteAllSources(e0);
1011 this->WriteEmbeddedResourceGroup(e0);
1012 this->WriteXamlFilesGroup(e0);
1013 this->WriteDotNetReferences(e0);
1014 this->WritePackageReferences(e0);
1015 this->WriteProjectReferences(e0);
1018 void cmVisualStudio10TargetGenerator::WriteCommonPropertyGroupGlobals(Elem& e1)
1020 e1.Attribute("Label", "Globals");
1021 e1.Element("ProjectGuid", cmStrCat('{', this->GUID, '}'));
1023 cmValue vsProjectTypes =
1024 this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
1025 if (vsProjectTypes) {
1026 const char* tagName = "ProjectTypes";
1027 if (this->ProjectType == VsProjectType::csproj) {
1028 tagName = "ProjectTypeGuids";
1030 e1.Element(tagName, *vsProjectTypes);
1033 cmValue vsGlobalKeyword =
1034 this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD");
1035 if (!vsGlobalKeyword) {
1036 if (this->GlobalGenerator->TargetsAndroid()) {
1037 e1.Element("Keyword", "Android");
1038 } else {
1039 e1.Element("Keyword", "Win32Proj");
1041 } else {
1042 e1.Element("Keyword", *vsGlobalKeyword);
1045 cmValue vsGlobalRootNamespace =
1046 this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE");
1047 if (vsGlobalRootNamespace) {
1048 e1.Element("RootNamespace", *vsGlobalRootNamespace);
1051 std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
1052 for (std::string const& keyIt : keys) {
1053 static const cm::string_view prefix = "VS_GLOBAL_";
1054 if (!cmHasPrefix(keyIt, prefix)) {
1055 continue;
1057 cm::string_view globalKey = cm::string_view(keyIt).substr(prefix.length());
1058 // Skip invalid or separately-handled properties.
1059 if (globalKey.empty() || globalKey == "PROJECT_TYPES"_s ||
1060 globalKey == "ROOTNAMESPACE"_s || globalKey == "KEYWORD"_s) {
1061 continue;
1063 cmValue value = this->GeneratorTarget->GetProperty(keyIt);
1064 if (!value) {
1065 continue;
1067 e1.Element(globalKey, *value);
1071 void cmVisualStudio10TargetGenerator::WritePackageReferences(Elem& e0)
1073 std::vector<std::string> packageReferences =
1074 this->GeneratorTarget->GetPackageReferences();
1076 if (!packageReferences.empty()) {
1077 Elem e1(e0, "ItemGroup");
1078 for (std::string const& ri : packageReferences) {
1079 size_t versionIndex = ri.find_last_of('_');
1080 if (versionIndex != std::string::npos) {
1081 Elem e2(e1, "PackageReference");
1082 e2.Attribute("Include", ri.substr(0, versionIndex));
1083 e2.Attribute("Version", ri.substr(versionIndex + 1));
1089 void cmVisualStudio10TargetGenerator::WriteDotNetReferences(Elem& e0)
1091 cmList references;
1092 if (cmValue vsDotNetReferences =
1093 this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
1094 references.assign(*vsDotNetReferences);
1096 cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
1097 for (auto const& i : props.GetList()) {
1098 static const cm::string_view vsDnRef = "VS_DOTNET_REFERENCE_";
1099 if (cmHasPrefix(i.first, vsDnRef)) {
1100 std::string path = i.second;
1101 if (!cmsys::SystemTools::FileIsFullPath(path)) {
1102 path =
1103 cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', path);
1105 ConvertToWindowsSlash(path);
1106 this->DotNetHintReferences[""].emplace_back(
1107 DotNetHintReference(i.first.substr(vsDnRef.length()), path));
1110 if (!references.empty() || !this->DotNetHintReferences.empty()) {
1111 Elem e1(e0, "ItemGroup");
1112 for (auto const& ri : references) {
1113 // if the entry from VS_DOTNET_REFERENCES is an existing file, generate
1114 // a new hint-reference and name it from the filename
1115 if (cmsys::SystemTools::FileExists(ri, true)) {
1116 std::string name =
1117 cmsys::SystemTools::GetFilenameWithoutLastExtension(ri);
1118 std::string path = ri;
1119 ConvertToWindowsSlash(path);
1120 this->DotNetHintReferences[""].emplace_back(
1121 DotNetHintReference(name, path));
1122 } else {
1123 this->WriteDotNetReference(e1, ri, "", "");
1126 for (const auto& h : this->DotNetHintReferences) {
1127 // DotNetHintReferences is also populated from AddLibraries().
1128 // The configuration specific hint references are added there.
1129 for (const auto& i : h.second) {
1130 this->WriteDotNetReference(e1, i.first, i.second, h.first);
1136 void cmVisualStudio10TargetGenerator::WriteDotNetReference(
1137 Elem& e1, std::string const& ref, std::string const& hint,
1138 std::string const& config)
1140 Elem e2(e1, "Reference");
1141 // If 'config' is not empty, the reference is only added for the given
1142 // configuration. This is used when referencing imported managed assemblies.
1143 // See also cmVisualStudio10TargetGenerator::AddLibraries().
1144 if (!config.empty()) {
1145 e2.Attribute("Condition", this->CalcCondition(config));
1147 e2.Attribute("Include", ref);
1148 e2.Element("CopyLocalSatelliteAssemblies", "true");
1149 e2.Element("ReferenceOutputAssembly", "true");
1150 if (!hint.empty()) {
1151 const char* privateReference = "True";
1152 if (cmValue value = this->GeneratorTarget->GetProperty(
1153 "VS_DOTNET_REFERENCES_COPY_LOCAL")) {
1154 if (value.IsOff()) {
1155 privateReference = "False";
1158 e2.Element("Private", privateReference);
1159 e2.Element("HintPath", hint);
1161 this->WriteDotNetReferenceCustomTags(e2, ref);
1164 void cmVisualStudio10TargetGenerator::WriteFrameworkReferences(Elem& e0)
1166 cmList references;
1167 if (cmValue vsFrameworkReferences =
1168 this->GeneratorTarget->GetProperty("VS_FRAMEWORK_REFERENCES")) {
1169 references.assign(*vsFrameworkReferences);
1172 Elem e1(e0, "ItemGroup");
1173 for (auto const& ref : references) {
1174 Elem e2(e1, "FrameworkReference");
1175 e2.Attribute("Include", ref);
1179 void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0)
1181 cmValue imports =
1182 this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT");
1183 if (imports) {
1184 cmList argsSplit{ *imports };
1185 for (auto& path : argsSplit) {
1186 if (!cmsys::SystemTools::FileIsFullPath(path)) {
1187 path =
1188 cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', path);
1190 ConvertToWindowsSlash(path);
1191 Elem e1(e0, "Import");
1192 e1.Attribute("Project", path);
1197 void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
1198 Elem& e2, std::string const& ref)
1201 static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
1202 static const std::string refpropInfix = "_TAG_";
1203 const std::string refPropFullPrefix =
1204 cmStrCat(refpropPrefix, ref, refpropInfix);
1205 using CustomTags = std::map<std::string, std::string>;
1206 CustomTags tags;
1207 cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
1208 for (const auto& i : props.GetList()) {
1209 if (cmHasPrefix(i.first, refPropFullPrefix) && !i.second.empty()) {
1210 tags[i.first.substr(refPropFullPrefix.length())] = i.second;
1213 for (auto const& tag : tags) {
1214 e2.Element(tag.first, tag.second);
1218 void cmVisualStudio10TargetGenerator::WriteDotNetDocumentationFile(Elem& e0)
1220 std::string const& documentationFile =
1221 this->GeneratorTarget->GetSafeProperty("VS_DOTNET_DOCUMENTATION_FILE");
1223 if (this->ProjectType == VsProjectType::csproj &&
1224 !documentationFile.empty()) {
1225 Elem e1(e0, "PropertyGroup");
1226 Elem e2(e1, "DocumentationFile");
1227 e2.Content(documentationFile);
1231 void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup(Elem& e0)
1233 if (!this->ResxObjs.empty()) {
1234 Elem e1(e0, "ItemGroup");
1235 std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
1236 ConvertToWindowsSlash(srcDir);
1237 for (cmSourceFile const* oi : this->ResxObjs) {
1238 std::string obj = oi->GetFullPath();
1239 ConvertToWindowsSlash(obj);
1240 bool useRelativePath = false;
1241 if (this->ProjectType == VsProjectType::csproj && this->InSourceBuild) {
1242 // If we do an in-source build and the resource file is in a
1243 // subdirectory
1244 // of the .csproj file, we have to use relative pathnames, otherwise
1245 // visual studio does not show the file in the IDE. Sorry.
1246 if (cmHasPrefix(obj, srcDir)) {
1247 obj = this->ConvertPath(obj, true);
1248 ConvertToWindowsSlash(obj);
1249 useRelativePath = true;
1252 Elem e2(e1, "EmbeddedResource");
1253 e2.Attribute("Include", obj);
1255 if (this->ProjectType != VsProjectType::csproj) {
1256 std::string hFileName =
1257 cmStrCat(obj.substr(0, obj.find_last_of('.')), ".h");
1258 e2.Element("DependentUpon", hFileName);
1260 for (std::string const& c : this->Configurations) {
1261 std::string s;
1262 if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
1263 // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
1264 this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
1265 s = "$(RootNamespace).";
1267 s += "%(Filename).resources";
1268 e2.WritePlatformConfigTag("LogicalName", this->CalcCondition(c), s);
1270 } else {
1271 std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
1272 ConvertToWindowsSlash(binDir);
1273 // If the resource was NOT added using a relative path (which should
1274 // be the default), we have to provide a link here
1275 if (!useRelativePath) {
1276 std::string link = this->GetCSharpSourceLink(oi);
1277 if (link.empty()) {
1278 link = cmsys::SystemTools::GetFilenameName(obj);
1280 e2.Element("Link", link);
1282 // Determine if this is a generated resource from a .Designer.cs file
1283 std::string designerResource = cmStrCat(
1284 cmSystemTools::GetFilenamePath(oi->GetFullPath()), '/',
1285 cmSystemTools::GetFilenameWithoutLastExtension(oi->GetFullPath()),
1286 ".Designer.cs");
1287 if (cmsys::SystemTools::FileExists(designerResource)) {
1288 std::string generator = "PublicResXFileCodeGenerator";
1289 if (cmValue g = oi->GetProperty("VS_RESOURCE_GENERATOR")) {
1290 generator = *g;
1292 if (!generator.empty()) {
1293 e2.Element("Generator", generator);
1294 if (cmHasPrefix(designerResource, srcDir)) {
1295 designerResource.erase(0, srcDir.length());
1296 } else if (cmHasPrefix(designerResource, binDir)) {
1297 designerResource.erase(0, binDir.length());
1298 } else {
1299 designerResource =
1300 cmsys::SystemTools::GetFilenameName(designerResource);
1302 ConvertToWindowsSlash(designerResource);
1303 e2.Element("LastGenOutput", designerResource);
1306 const cmPropertyMap& props = oi->GetProperties();
1307 for (const std::string& p : props.GetKeys()) {
1308 static const cm::string_view propNamePrefix = "VS_CSHARP_";
1309 if (cmHasPrefix(p, propNamePrefix)) {
1310 cm::string_view tagName =
1311 cm::string_view(p).substr(propNamePrefix.length());
1312 if (!tagName.empty()) {
1313 cmValue value = props.GetPropertyValue(p);
1314 if (cmNonempty(value)) {
1315 e2.Element(tagName, *value);
1325 void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup(Elem& e0)
1327 if (!this->XamlObjs.empty()) {
1328 Elem e1(e0, "ItemGroup");
1329 for (cmSourceFile const* oi : this->XamlObjs) {
1330 std::string obj = oi->GetFullPath();
1331 std::string xamlType;
1332 cmValue xamlTypeProperty = oi->GetProperty("VS_XAML_TYPE");
1333 if (xamlTypeProperty) {
1334 xamlType = *xamlTypeProperty;
1335 } else {
1336 xamlType = "Page";
1339 Elem e2(e1, xamlType);
1340 this->WriteSource(e2, oi);
1341 e2.SetHasElements();
1342 e2.Element("SubType", "Designer");
1347 void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences(Elem& e0)
1349 if (this->MSTools) {
1350 if (this->GlobalGenerator->TargetsWindowsPhone() &&
1351 this->GlobalGenerator->GetSystemVersion() == "8.0"_s) {
1352 Elem(e0, "Import")
1353 .Attribute("Project",
1354 "$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
1355 "$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
1356 "$(TargetPlatformVersion).targets");
1361 void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences(Elem& e1)
1363 for (TargetsFileAndConfigs const& tac : this->TargetsFileAndConfigsVec) {
1364 std::ostringstream oss;
1365 oss << "Exists('" << tac.File << "')";
1366 if (!tac.Configs.empty()) {
1367 oss << " And (";
1368 for (size_t j = 0; j < tac.Configs.size(); ++j) {
1369 if (j > 0) {
1370 oss << " Or ";
1372 oss << "'$(Configuration)'=='" << tac.Configs[j] << '\'';
1374 oss << ')';
1377 Elem(e1, "Import")
1378 .Attribute("Project", tac.File)
1379 .Attribute("Condition", oss.str());
1383 void cmVisualStudio10TargetGenerator::WriteWinRTReferences(Elem& e0)
1385 cmList references;
1386 if (cmValue vsWinRTReferences =
1387 this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) {
1388 references.assign(*vsWinRTReferences);
1391 if (this->GlobalGenerator->TargetsWindowsPhone() &&
1392 this->GlobalGenerator->GetSystemVersion() == "8.0"_s &&
1393 references.empty()) {
1394 references.push_back(std::string{ "platform.winmd" });
1396 if (!references.empty()) {
1397 Elem e1(e0, "ItemGroup");
1398 for (auto const& ri : references) {
1399 Elem e2(e1, "Reference");
1400 e2.Attribute("Include", ri);
1401 e2.Element("IsWinMDFile", "true");
1406 // ConfigurationType Application, Utility StaticLibrary DynamicLibrary
1408 void cmVisualStudio10TargetGenerator::WriteProjectConfigurations(Elem& e0)
1410 Elem e1(e0, "ItemGroup");
1411 e1.Attribute("Label", "ProjectConfigurations");
1412 for (std::string const& c : this->Configurations) {
1413 Elem e2(e1, "ProjectConfiguration");
1414 e2.Attribute("Include", cmStrCat(c, '|', this->Platform));
1415 e2.Element("Configuration", c);
1416 e2.Element("Platform", this->Platform);
1420 void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues(Elem& e0)
1422 for (std::string const& c : this->Configurations) {
1423 Elem e1(e0, "PropertyGroup");
1424 e1.Attribute("Condition", this->CalcCondition(c));
1425 e1.Attribute("Label", "Configuration");
1427 if (this->ProjectType != VsProjectType::csproj) {
1428 std::string configType;
1429 if (cmValue vsConfigurationType =
1430 this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
1431 configType = cmGeneratorExpression::Evaluate(*vsConfigurationType,
1432 this->LocalGenerator, c);
1433 } else {
1434 switch (this->GeneratorTarget->GetType()) {
1435 case cmStateEnums::SHARED_LIBRARY:
1436 case cmStateEnums::MODULE_LIBRARY:
1437 configType = "DynamicLibrary";
1438 break;
1439 case cmStateEnums::OBJECT_LIBRARY:
1440 case cmStateEnums::STATIC_LIBRARY:
1441 configType = "StaticLibrary";
1442 break;
1443 case cmStateEnums::EXECUTABLE:
1444 if (this->NsightTegra &&
1445 !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
1446 // Android executables are .so too.
1447 configType = "DynamicLibrary";
1448 } else if (this->Android) {
1449 configType = "DynamicLibrary";
1450 } else {
1451 configType = "Application";
1453 break;
1454 case cmStateEnums::UTILITY:
1455 case cmStateEnums::INTERFACE_LIBRARY:
1456 case cmStateEnums::GLOBAL_TARGET:
1457 if (this->NsightTegra) {
1458 // Tegra-Android platform does not understand "Utility".
1459 configType = "StaticLibrary";
1460 } else {
1461 configType = "Utility";
1463 break;
1464 case cmStateEnums::UNKNOWN_LIBRARY:
1465 break;
1468 e1.Element("ConfigurationType", configType);
1471 if (this->MSTools) {
1472 if (!this->Managed) {
1473 this->WriteMSToolConfigurationValues(e1, c);
1474 } else {
1475 this->WriteMSToolConfigurationValuesManaged(e1, c);
1477 } else if (this->NsightTegra) {
1478 this->WriteNsightTegraConfigurationValues(e1, c);
1479 } else if (this->Android) {
1480 this->WriteAndroidConfigurationValues(e1, c);
1485 void cmVisualStudio10TargetGenerator::WriteCEDebugProjectConfigurationValues(
1486 Elem& e0)
1488 if (!this->GlobalGenerator->TargetsWindowsCE()) {
1489 return;
1491 cmValue additionalFiles =
1492 this->GeneratorTarget->GetProperty("DEPLOYMENT_ADDITIONAL_FILES");
1493 cmValue remoteDirectory =
1494 this->GeneratorTarget->GetProperty("DEPLOYMENT_REMOTE_DIRECTORY");
1495 if (!(additionalFiles || remoteDirectory)) {
1496 return;
1498 for (std::string const& c : this->Configurations) {
1499 Elem e1(e0, "PropertyGroup");
1500 e1.Attribute("Condition", this->CalcCondition(c));
1502 if (remoteDirectory) {
1503 e1.Element("RemoteDirectory", *remoteDirectory);
1505 if (additionalFiles) {
1506 e1.Element("CEAdditionalFiles", *additionalFiles);
1511 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
1512 Elem& e1, std::string const& config)
1514 cmValue mfcFlag = this->Makefile->GetDefinition("CMAKE_MFC_FLAG");
1515 if (mfcFlag) {
1516 std::string const mfcFlagValue =
1517 cmGeneratorExpression::Evaluate(*mfcFlag, this->LocalGenerator, config);
1519 std::string useOfMfcValue = "false";
1520 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
1521 if (mfcFlagValue == "1"_s) {
1522 useOfMfcValue = "Static";
1523 } else if (mfcFlagValue == "2"_s) {
1524 useOfMfcValue = "Dynamic";
1527 e1.Element("UseOfMfc", useOfMfcValue);
1530 if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
1531 this->ClOptions[config]->UsingUnicode()) ||
1532 this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
1533 this->GlobalGenerator->TargetsWindowsPhone() ||
1534 this->GlobalGenerator->TargetsWindowsStore() ||
1535 this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
1536 e1.Element("CharacterSet", "Unicode");
1537 } else if (this->GeneratorTarget->GetType() <=
1538 cmStateEnums::OBJECT_LIBRARY &&
1539 this->ClOptions[config]->UsingSBCS()) {
1540 e1.Element("CharacterSet", "NotSet");
1541 } else {
1542 e1.Element("CharacterSet", "MultiByte");
1545 this->WriteMSToolConfigurationValuesCommon(e1, config);
1547 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
1548 this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
1549 e1.Element("WindowsAppContainer", "true");
1551 if (this->IPOEnabledConfigurations.count(config) > 0) {
1552 e1.Element("WholeProgramOptimization", "true");
1554 if (this->ASanEnabledConfigurations.find(config) !=
1555 this->ASanEnabledConfigurations.end()) {
1556 e1.Element("EnableAsan", "true");
1558 if (this->FuzzerEnabledConfigurations.find(config) !=
1559 this->FuzzerEnabledConfigurations.end()) {
1560 e1.Element("EnableFuzzer", "true");
1563 auto s = this->SpectreMitigation.find(config);
1564 if (s != this->SpectreMitigation.end()) {
1565 e1.Element("SpectreMitigation", s->second);
1570 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
1571 Elem& e1, std::string const& config)
1573 if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
1574 return;
1577 Options& o = *(this->ClOptions[config]);
1579 if (o.UsingDebugInfo()) {
1580 e1.Element("DebugSymbols", "true");
1581 e1.Element("DefineDebug", "true");
1584 std::string outDir =
1585 cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
1586 ConvertToWindowsSlash(outDir);
1587 e1.Element("OutputPath", outDir);
1589 if (o.HasFlag("Platform")) {
1590 e1.Element("PlatformTarget", o.GetFlag("Platform"));
1591 o.RemoveFlag("Platform");
1594 this->WriteMSToolConfigurationValuesCommon(e1, config);
1596 std::string assemblyName = GetAssemblyName(config);
1597 e1.Element("AssemblyName", assemblyName);
1599 if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
1600 e1.Element("StartAction", "Program");
1601 e1.Element("StartProgram", cmStrCat(outDir, assemblyName, ".exe"));
1604 OptionsHelper oh(o, e1);
1605 oh.OutputFlagMap();
1608 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesCommon(
1609 Elem& e1, std::string const& config)
1611 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1612 if (cmValue projectToolsetOverride =
1613 this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1614 e1.Element("PlatformToolset", *projectToolsetOverride);
1615 } else if (const char* toolset = gg->GetPlatformToolset()) {
1616 e1.Element("PlatformToolset", toolset);
1619 cm::optional<bool> maybeUseDebugLibraries;
1620 if (cmValue useDebugLibrariesProp =
1621 this->GeneratorTarget->GetProperty("VS_USE_DEBUG_LIBRARIES")) {
1622 // The project explicitly specified a value for this target.
1623 // An empty string suppresses generation of the setting altogether.
1624 std::string const useDebugLibraries = cmGeneratorExpression::Evaluate(
1625 *useDebugLibrariesProp, this->LocalGenerator, config);
1626 if (!useDebugLibraries.empty()) {
1627 maybeUseDebugLibraries = cmIsOn(useDebugLibraries);
1629 } else if (this->GeneratorTarget->GetPolicyStatusCMP0162() ==
1630 cmPolicies::NEW) {
1631 // The project did not explicitly specify a value for this target.
1632 // If the target compiles sources for a known MSVC runtime library,
1633 // base our default value on that.
1634 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
1635 maybeUseDebugLibraries = this->ClOptions[config]->UsingDebugRuntime();
1637 // For other targets, such as UTILITY targets, base our default
1638 // on the configuration name.
1639 if (!maybeUseDebugLibraries) {
1640 maybeUseDebugLibraries = cmSystemTools::UpperCase(config) == "DEBUG"_s;
1643 if (maybeUseDebugLibraries) {
1644 if (*maybeUseDebugLibraries) {
1645 e1.Element("UseDebugLibraries", "true");
1646 } else {
1647 e1.Element("UseDebugLibraries", "false");
1652 //----------------------------------------------------------------------------
1653 void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
1654 Elem& e1, std::string const&)
1656 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1657 const char* toolset = gg->GetPlatformToolset();
1658 e1.Element("NdkToolchainVersion", toolset ? toolset : "Default");
1659 if (cmValue minApi = this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) {
1660 e1.Element("AndroidMinAPI", cmStrCat("android-", *minApi));
1662 if (cmValue api = this->GeneratorTarget->GetProperty("ANDROID_API")) {
1663 e1.Element("AndroidTargetAPI", cmStrCat("android-", *api));
1666 if (cmValue cpuArch = this->GeneratorTarget->GetProperty("ANDROID_ARCH")) {
1667 e1.Element("AndroidArch", *cpuArch);
1670 if (cmValue stlType =
1671 this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
1672 e1.Element("AndroidStlType", *stlType);
1676 void cmVisualStudio10TargetGenerator::WriteAndroidConfigurationValues(
1677 Elem& e1, std::string const&)
1679 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1680 if (cmValue projectToolsetOverride =
1681 this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1682 e1.Element("PlatformToolset", *projectToolsetOverride);
1683 } else if (const char* toolset = gg->GetPlatformToolset()) {
1684 e1.Element("PlatformToolset", toolset);
1686 if (cmValue stlType =
1687 this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
1688 if (*stlType != "none"_s) {
1689 e1.Element("UseOfStl", *stlType);
1692 std::string const& apiLevel = gg->GetSystemVersion();
1693 if (!apiLevel.empty()) {
1694 e1.Element("AndroidAPILevel", cmStrCat("android-", apiLevel));
1698 void cmVisualStudio10TargetGenerator::WriteCustomCommands(Elem& e0)
1700 this->CSharpCustomCommandNames.clear();
1702 cmSourceFile const* srcCMakeLists =
1703 this->LocalGenerator->CreateVCProjBuildRule();
1705 for (cmGeneratorTarget::AllConfigSource const& si :
1706 this->GeneratorTarget->GetAllConfigSources()) {
1707 if (si.Source == srcCMakeLists) {
1708 // Skip explicit reference to CMakeLists.txt source.
1709 continue;
1711 this->WriteCustomCommand(e0, si.Source);
1714 // Add CMakeLists.txt file with rule to re-run CMake for user convenience.
1715 if (this->GeneratorTarget->GetType() != cmStateEnums::GLOBAL_TARGET &&
1716 this->GeneratorTarget->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
1717 if (srcCMakeLists) {
1718 // Write directly rather than through WriteCustomCommand because
1719 // we do not want the de-duplication and it has no dependencies.
1720 if (cmCustomCommand const* command = srcCMakeLists->GetCustomCommand()) {
1721 this->WriteCustomRule(e0, srcCMakeLists, *command);
1727 void cmVisualStudio10TargetGenerator::WriteCustomCommand(
1728 Elem& e0, cmSourceFile const* sf)
1730 if (this->LocalGenerator->GetSourcesVisited(this->GeneratorTarget)
1731 .insert(sf)
1732 .second) {
1733 if (std::vector<cmSourceFile*> const* depends =
1734 this->GeneratorTarget->GetSourceDepends(sf)) {
1735 for (cmSourceFile const* di : *depends) {
1736 this->WriteCustomCommand(e0, di);
1739 if (cmCustomCommand const* command = sf->GetCustomCommand()) {
1740 // C# projects write their <Target> within WriteCustomRule()
1741 this->WriteCustomRule(e0, sf, *command);
1746 void cmVisualStudio10TargetGenerator::WriteCustomRule(
1747 Elem& e0, cmSourceFile const* source, cmCustomCommand const& command)
1749 std::string sourcePath = source->GetFullPath();
1750 // VS 10 will always rebuild a custom command attached to a .rule
1751 // file that doesn't exist so create the file explicitly.
1752 if (source->GetPropertyAsBool("__CMAKE_RULE")) {
1753 if (!cmSystemTools::FileExists(sourcePath)) {
1754 // Make sure the path exists for the file
1755 std::string path = cmSystemTools::GetFilenamePath(sourcePath);
1756 cmSystemTools::MakeDirectory(path);
1757 cmsys::ofstream fout(sourcePath.c_str());
1758 if (fout) {
1759 fout << "# generated from CMake\n";
1760 fout.flush();
1761 fout.close();
1762 // Force given file to have a very old timestamp, thus
1763 // preventing dependent rebuilds.
1764 this->ForceOld(sourcePath);
1765 } else {
1766 cmSystemTools::Error(cmStrCat("Could not create file: [", sourcePath,
1767 "] ",
1768 cmSystemTools::GetLastSystemError()));
1772 cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
1774 std::unique_ptr<Elem> spe1;
1775 std::unique_ptr<Elem> spe2;
1776 if (this->ProjectType != VsProjectType::csproj) {
1777 spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
1778 spe2 = cm::make_unique<Elem>(*spe1, "CustomBuild");
1779 this->WriteSource(*spe2, source);
1780 spe2->SetHasElements();
1781 if (command.GetStdPipesUTF8()) {
1782 this->WriteStdOutEncodingUtf8(*spe2);
1784 } else {
1785 Elem e1(e0, "ItemGroup");
1786 Elem e2(e1, "None");
1787 this->WriteSource(e2, source);
1788 e2.SetHasElements();
1790 for (std::string const& c : this->Configurations) {
1791 cmCustomCommandGenerator ccg(command, c, lg, true);
1792 std::string comment = lg->ConstructComment(ccg);
1793 comment = cmVS10EscapeComment(comment);
1794 std::string script = lg->ConstructScript(ccg);
1795 bool symbolic = false;
1796 // input files for custom command
1797 std::stringstream additional_inputs;
1799 const char* sep = "";
1800 if (this->ProjectType == VsProjectType::csproj) {
1801 // csproj files do not attach the command to a specific file
1802 // so the primary input must be listed explicitly.
1803 additional_inputs << source->GetFullPath();
1804 sep = ";";
1807 // Avoid listing an input more than once.
1808 std::set<std::string> unique_inputs;
1809 // The source is either implicit an input or has been added above.
1810 unique_inputs.insert(source->GetFullPath());
1812 for (std::string const& d : ccg.GetDepends()) {
1813 std::string dep;
1814 if (lg->GetRealDependency(d, c, dep)) {
1815 if (!unique_inputs.insert(dep).second) {
1816 // already listed
1817 continue;
1819 ConvertToWindowsSlash(dep);
1820 additional_inputs << sep << dep;
1821 sep = ";";
1822 if (!symbolic) {
1823 if (cmSourceFile* sf = this->Makefile->GetSource(
1824 dep, cmSourceFileLocationKind::Known)) {
1825 symbolic = sf->GetPropertyAsBool("SYMBOLIC");
1829 // Without UpToDateCheckInput VS will ignore the dependency files
1830 // when doing it's fast up-to-date check and the command will not run
1831 if (this->ProjectType == VsProjectType::csproj &&
1832 this->GeneratorTarget->IsDotNetSdkTarget()) {
1833 Elem e1(e0, "ItemGroup");
1834 Elem e2(e1, "UpToDateCheckInput");
1835 e2.Attribute("Include", dep);
1839 if (this->ProjectType != VsProjectType::csproj) {
1840 additional_inputs << sep << "%(AdditionalInputs)";
1843 // output files for custom command
1844 std::stringstream outputs;
1846 const char* sep = "";
1847 for (std::string const& o : ccg.GetOutputs()) {
1848 std::string out = o;
1849 ConvertToWindowsSlash(out);
1850 outputs << sep << out;
1851 sep = ";";
1852 if (!symbolic) {
1853 if (cmSourceFile* sf = this->Makefile->GetSource(
1854 o, cmSourceFileLocationKind::Known)) {
1855 symbolic = sf->GetPropertyAsBool("SYMBOLIC");
1860 script += lg->FinishConstructScript(this->ProjectType);
1861 if (this->ProjectType == VsProjectType::csproj) {
1862 cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
1863 std::string name =
1864 cmStrCat("CustomCommand_", c, '_', hasher.HashString(sourcePath));
1865 this->WriteCustomRuleCSharp(e0, c, name, script, additional_inputs.str(),
1866 outputs.str(), comment, ccg);
1867 } else {
1868 BuildInParallel buildInParallel = BuildInParallel::No;
1869 if (command.GetCMP0147Status() == cmPolicies::NEW &&
1870 !command.GetUsesTerminal() &&
1871 !(command.HasMainDependency() && source->GetIsGenerated())) {
1872 buildInParallel = BuildInParallel::Yes;
1874 this->WriteCustomRuleCpp(*spe2, c, script, additional_inputs.str(),
1875 outputs.str(), comment, ccg, symbolic,
1876 buildInParallel);
1881 void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
1882 Elem& e2, std::string const& config, std::string const& script,
1883 std::string const& additional_inputs, std::string const& outputs,
1884 std::string const& comment, cmCustomCommandGenerator const& ccg,
1885 bool symbolic, BuildInParallel buildInParallel)
1887 const std::string cond = this->CalcCondition(config);
1888 if (buildInParallel == BuildInParallel::Yes &&
1889 this->GlobalGenerator->IsBuildInParallelSupported()) {
1890 e2.WritePlatformConfigTag("BuildInParallel", cond, "true");
1892 e2.WritePlatformConfigTag("Message", cond, comment);
1893 e2.WritePlatformConfigTag("Command", cond, script);
1894 e2.WritePlatformConfigTag("AdditionalInputs", cond, additional_inputs);
1895 e2.WritePlatformConfigTag("Outputs", cond, outputs);
1896 // Turn off linking of custom command outputs.
1897 e2.WritePlatformConfigTag("LinkObjects", cond, "false");
1898 if (symbolic &&
1899 this->LocalGenerator->GetVersion() >=
1900 cmGlobalVisualStudioGenerator::VSVersion::VS16) {
1901 // VS >= 16.4 warn if outputs are not created, but one of our
1902 // outputs is marked SYMBOLIC and not expected to be created.
1903 e2.WritePlatformConfigTag("VerifyInputsAndOutputsExist", cond, "false");
1906 std::string depfile = ccg.GetFullDepfile();
1907 if (!depfile.empty()) {
1908 this->HaveCustomCommandDepfile = true;
1909 std::string internal_depfile = ccg.GetInternalDepfile();
1910 ConvertToWindowsSlash(internal_depfile);
1911 e2.WritePlatformConfigTag("DepFileAdditionalInputsFile", cond,
1912 internal_depfile);
1916 void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
1917 Elem& e0, std::string const& config, std::string const& name,
1918 std::string const& script, std::string const& inputs,
1919 std::string const& outputs, std::string const& comment,
1920 cmCustomCommandGenerator const& ccg)
1922 if (!ccg.GetFullDepfile().empty()) {
1923 this->Makefile->IssueMessage(
1924 MessageType::FATAL_ERROR,
1925 cmStrCat("CSharp target \"", this->GeneratorTarget->GetName(),
1926 "\" does not support add_custom_command DEPFILE."));
1928 this->CSharpCustomCommandNames.insert(name);
1929 Elem e1(e0, "Target");
1930 e1.Attribute("Condition", cmStrCat("'$(Configuration)' == '", config, '\''));
1931 e1.S << "\n Name=\"" << name << "\"";
1932 e1.S << "\n Inputs=\"" << cmVS10EscapeAttr(inputs) << "\"";
1933 e1.S << "\n Outputs=\"" << cmVS10EscapeAttr(outputs) << "\"";
1935 // Run before sources are compiled...
1936 e1.S << "\n BeforeTargets=\"CoreCompile\""; // BeforeBuild
1937 // ...but after output directory has been created
1938 e1.S << "\n DependsOnTargets=\"PrepareForBuild\"";
1940 if (!comment.empty()) {
1941 Elem(e1, "Exec").Attribute("Command", cmStrCat("echo ", comment));
1943 Elem(e1, "Exec").Attribute("Command", script);
1946 std::string cmVisualStudio10TargetGenerator::ConvertPath(
1947 std::string const& path, bool forceRelative)
1949 return forceRelative
1950 ? cmSystemTools::RelativePath(
1951 this->LocalGenerator->GetCurrentBinaryDirectory(), path)
1952 : path;
1955 static void ConvertToWindowsSlash(std::string& s)
1957 // first convert all of the slashes
1958 for (auto& ch : s) {
1959 if (ch == '/') {
1960 ch = '\\';
1965 void cmVisualStudio10TargetGenerator::WriteGroups()
1967 if (this->ProjectType == VsProjectType::csproj) {
1968 return;
1971 // collect up group information
1972 std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
1974 std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
1975 this->GeneratorTarget->GetAllConfigSources();
1977 std::set<cmSourceGroup const*> groupsUsed;
1978 for (cmGeneratorTarget::AllConfigSource const& si : sources) {
1979 std::string const& source = si.Source->GetFullPath();
1980 cmSourceGroup* sourceGroup =
1981 this->Makefile->FindSourceGroup(source, sourceGroups);
1982 groupsUsed.insert(sourceGroup);
1985 if (cmSourceFile const* srcCMakeLists =
1986 this->LocalGenerator->CreateVCProjBuildRule()) {
1987 std::string const& source = srcCMakeLists->GetFullPath();
1988 cmSourceGroup* sourceGroup =
1989 this->Makefile->FindSourceGroup(source, sourceGroups);
1990 groupsUsed.insert(sourceGroup);
1993 this->AddMissingSourceGroups(groupsUsed, sourceGroups);
1995 // Write out group file
1996 std::string path = cmStrCat(
1997 this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->Name,
1998 computeProjectFileExtension(this->GeneratorTarget), ".filters");
1999 cmGeneratedFileStream fout(path);
2000 fout.SetCopyIfDifferent(true);
2001 char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
2002 fout.write(magic, 3);
2004 fout << R"(<?xml version="1.0" encoding=")"
2005 << this->GlobalGenerator->Encoding() << "\"?>";
2007 Elem e0(fout, "Project");
2008 e0.Attribute("ToolsVersion", this->GlobalGenerator->GetToolsVersion());
2009 e0.Attribute("xmlns",
2010 "http://schemas.microsoft.com/developer/msbuild/2003");
2012 for (auto const& ti : this->Tools) {
2013 this->WriteGroupSources(e0, ti.first, ti.second, sourceGroups);
2016 // Added files are images and the manifest.
2017 if (!this->AddedFiles.empty()) {
2018 Elem e1(e0, "ItemGroup");
2019 e1.SetHasElements();
2020 for (std::string const& oi : this->AddedFiles) {
2021 std::string fileName =
2022 cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(oi));
2023 if (fileName == "wmappmanifest.xml"_s) {
2024 Elem e2(e1, "XML");
2025 e2.Attribute("Include", oi);
2026 e2.Element("Filter", "Resource Files");
2027 } else if (cmSystemTools::GetFilenameExtension(fileName) ==
2028 ".appxmanifest") {
2029 Elem e2(e1, "AppxManifest");
2030 e2.Attribute("Include", oi);
2031 e2.Element("Filter", "Resource Files");
2032 } else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx"_s) {
2033 Elem e2(e1, "None");
2034 e2.Attribute("Include", oi);
2035 e2.Element("Filter", "Resource Files");
2036 } else {
2037 Elem e2(e1, "Image");
2038 e2.Attribute("Include", oi);
2039 e2.Element("Filter", "Resource Files");
2044 if (!this->ResxObjs.empty()) {
2045 Elem e1(e0, "ItemGroup");
2046 for (cmSourceFile const* oi : this->ResxObjs) {
2047 std::string obj = oi->GetFullPath();
2048 ConvertToWindowsSlash(obj);
2049 Elem e2(e1, "EmbeddedResource");
2050 e2.Attribute("Include", obj);
2051 e2.Element("Filter", "Resource Files");
2055 Elem e1(e0, "ItemGroup");
2056 e1.SetHasElements();
2057 std::vector<cmSourceGroup const*> groupsVec(groupsUsed.begin(),
2058 groupsUsed.end());
2059 std::sort(groupsVec.begin(), groupsVec.end(),
2060 [](cmSourceGroup const* l, cmSourceGroup const* r) {
2061 return l->GetFullName() < r->GetFullName();
2063 for (cmSourceGroup const* sg : groupsVec) {
2064 std::string const& name = sg->GetFullName();
2065 if (!name.empty()) {
2066 std::string guidName = cmStrCat("SG_Filter_", name);
2067 std::string guid = this->GlobalGenerator->GetGUID(guidName);
2068 Elem e2(e1, "Filter");
2069 e2.Attribute("Include", name);
2070 e2.Element("UniqueIdentifier", cmStrCat('{', guid, '}'));
2074 if (!this->ResxObjs.empty() || !this->AddedFiles.empty()) {
2075 std::string guidName = "SG_Filter_Resource Files";
2076 std::string guid = this->GlobalGenerator->GetGUID(guidName);
2077 Elem e2(e1, "Filter");
2078 e2.Attribute("Include", "Resource Files");
2079 e2.Element("UniqueIdentifier", cmStrCat('{', guid, '}'));
2080 e2.Element("Extensions",
2081 "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;"
2082 "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms");
2086 if (cmValue p = this->GeneratorTarget->GetProperty("VS_FILTER_PROPS")) {
2087 auto props = *p;
2088 if (!props.empty()) {
2089 ConvertToWindowsSlash(props);
2090 Elem(e0, "Import")
2091 .Attribute("Project", props)
2092 .Attribute("Condition", cmStrCat("exists('", props, "')"))
2093 .Attribute("Label", "LocalAppDataPlatform");
2098 fout << '\n';
2100 if (fout.Close()) {
2101 this->GlobalGenerator->FileReplacedDuringGenerate(path);
2105 // Add to groupsUsed empty source groups that have non-empty children.
2106 void cmVisualStudio10TargetGenerator::AddMissingSourceGroups(
2107 std::set<cmSourceGroup const*>& groupsUsed,
2108 const std::vector<cmSourceGroup>& allGroups)
2110 for (cmSourceGroup const& current : allGroups) {
2111 std::vector<cmSourceGroup> const& children = current.GetGroupChildren();
2112 if (children.empty()) {
2113 continue; // the group is really empty
2116 this->AddMissingSourceGroups(groupsUsed, children);
2118 if (groupsUsed.count(&current) > 0) {
2119 continue; // group has already been added to set
2122 // check if it least one of the group's descendants is not empty
2123 // (at least one child must already have been added)
2124 auto child_it = children.begin();
2125 while (child_it != children.end()) {
2126 if (groupsUsed.count(&(*child_it)) > 0) {
2127 break; // found a child that was already added => add current group too
2129 child_it++;
2132 if (child_it == children.end()) {
2133 continue; // no descendants have source files => ignore this group
2136 groupsUsed.insert(&current);
2140 void cmVisualStudio10TargetGenerator::WriteGroupSources(
2141 Elem& e0, std::string const& name, ToolSources const& sources,
2142 std::vector<cmSourceGroup>& sourceGroups)
2144 Elem e1(e0, "ItemGroup");
2145 e1.SetHasElements();
2146 for (ToolSource const& s : sources) {
2147 cmSourceFile const* sf = s.SourceFile;
2148 std::string const& source = sf->GetFullPath();
2149 cmSourceGroup* sourceGroup =
2150 this->Makefile->FindSourceGroup(source, sourceGroups);
2151 std::string const& filter = sourceGroup->GetFullName();
2152 std::string path = this->ConvertPath(source, s.RelativePath);
2153 ConvertToWindowsSlash(path);
2154 Elem e2(e1, name);
2155 e2.Attribute("Include", path);
2156 if (!filter.empty()) {
2157 e2.Element("Filter", filter);
2162 void cmVisualStudio10TargetGenerator::WriteHeaderSource(
2163 Elem& e1, cmSourceFile const* sf, ConfigToSettings const& toolSettings)
2165 std::string const& fileName = sf->GetFullPath();
2166 Elem e2(e1, "ClInclude");
2167 this->WriteSource(e2, sf);
2168 if (this->IsResxHeader(fileName)) {
2169 e2.Element("FileType", "CppForm");
2170 } else if (this->IsXamlHeader(fileName)) {
2171 e2.Element("DependentUpon",
2172 fileName.substr(0, fileName.find_last_of('.')));
2174 this->FinishWritingSource(e2, toolSettings);
2177 void cmVisualStudio10TargetGenerator::ParseSettingsProperty(
2178 const std::string& settingsPropertyValue, ConfigToSettings& toolSettings)
2180 if (!settingsPropertyValue.empty()) {
2181 cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
2183 std::unique_ptr<cmCompiledGeneratorExpression> cge =
2184 ge.Parse(settingsPropertyValue);
2186 for (const std::string& config : this->Configurations) {
2187 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2189 cmList settings{ evaluated };
2190 for (const auto& setting : settings) {
2191 const std::string::size_type assignment = setting.find('=');
2192 if (assignment != std::string::npos) {
2193 const std::string propName = setting.substr(0, assignment);
2194 const std::string propValue = setting.substr(assignment + 1);
2196 if (!propValue.empty()) {
2197 toolSettings[config][propName] = propValue;
2205 bool cmVisualStudio10TargetGenerator::PropertyIsSameInAllConfigs(
2206 const ConfigToSettings& toolSettings, const std::string& propName)
2208 std::string firstPropValue;
2209 for (const auto& configToSettings : toolSettings) {
2210 const std::unordered_map<std::string, std::string>& settings =
2211 configToSettings.second;
2213 if (firstPropValue.empty()) {
2214 if (settings.find(propName) != settings.end()) {
2215 firstPropValue = settings.find(propName)->second;
2219 if (settings.find(propName) == settings.end()) {
2220 return false;
2223 if (settings.find(propName)->second != firstPropValue) {
2224 return false;
2228 return true;
2231 void cmVisualStudio10TargetGenerator::WriteExtraSource(
2232 Elem& e1, cmSourceFile const* sf, ConfigToSettings& toolSettings)
2234 bool toolHasSettings = false;
2235 const char* tool = "None";
2236 std::string settingsGenerator;
2237 std::string settingsLastGenOutput;
2238 std::string sourceLink;
2239 std::string subType;
2240 std::string copyToOutDir;
2241 std::string includeInVsix;
2242 std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
2244 if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
2245 toolHasSettings = true;
2247 if (ext == "hlsl"_s) {
2248 tool = "FXCompile";
2249 // Figure out the type of shader compiler to use.
2250 if (cmValue st = sf->GetProperty("VS_SHADER_TYPE")) {
2251 for (const std::string& config : this->Configurations) {
2252 toolSettings[config]["ShaderType"] = *st;
2255 // Figure out which entry point to use if any
2256 if (cmValue se = sf->GetProperty("VS_SHADER_ENTRYPOINT")) {
2257 for (const std::string& config : this->Configurations) {
2258 toolSettings[config]["EntryPointName"] = *se;
2261 // Figure out which shader model to use if any
2262 if (cmValue sm = sf->GetProperty("VS_SHADER_MODEL")) {
2263 for (const std::string& config : this->Configurations) {
2264 toolSettings[config]["ShaderModel"] = *sm;
2267 // Figure out which output header file to use if any
2268 if (cmValue ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
2269 for (const std::string& config : this->Configurations) {
2270 toolSettings[config]["HeaderFileOutput"] = *ohf;
2273 // Figure out which variable name to use if any
2274 if (cmValue vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
2275 for (const std::string& config : this->Configurations) {
2276 toolSettings[config]["VariableName"] = *vn;
2279 // Figure out if there's any additional flags to use
2280 if (cmValue saf = sf->GetProperty("VS_SHADER_FLAGS")) {
2281 cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
2282 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*saf);
2284 for (const std::string& config : this->Configurations) {
2285 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2287 if (!evaluated.empty()) {
2288 toolSettings[config]["AdditionalOptions"] = evaluated;
2292 // Figure out if debug information should be generated
2293 if (cmValue sed = sf->GetProperty("VS_SHADER_ENABLE_DEBUG")) {
2294 cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
2295 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sed);
2297 for (const std::string& config : this->Configurations) {
2298 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2300 if (!evaluated.empty()) {
2301 toolSettings[config]["EnableDebuggingInformation"] =
2302 cmIsOn(evaluated) ? "true" : "false";
2306 // Figure out if optimizations should be disabled
2307 if (cmValue sdo = sf->GetProperty("VS_SHADER_DISABLE_OPTIMIZATIONS")) {
2308 cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
2309 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sdo);
2311 for (const std::string& config : this->Configurations) {
2312 std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2314 if (!evaluated.empty()) {
2315 toolSettings[config]["DisableOptimizations"] =
2316 cmIsOn(evaluated) ? "true" : "false";
2320 if (cmValue sofn = sf->GetProperty("VS_SHADER_OBJECT_FILE_NAME")) {
2321 for (const std::string& config : this->Configurations) {
2322 toolSettings[config]["ObjectFileOutput"] = *sofn;
2325 } else if (ext == "jpg"_s || ext == "png"_s) {
2326 tool = "Image";
2327 } else if (ext == "resw"_s) {
2328 tool = "PRIResource";
2329 } else if (ext == "xml"_s) {
2330 tool = "XML";
2331 } else if (ext == "natvis"_s) {
2332 tool = "Natvis";
2333 } else if (ext == "settings"_s) {
2334 settingsLastGenOutput =
2335 cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
2336 std::size_t pos = settingsLastGenOutput.find(".settings");
2337 settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
2338 settingsGenerator = "SettingsSingleFileGenerator";
2339 toolHasSettings = true;
2340 } else if (ext == "vsixmanifest"_s) {
2341 subType = "Designer";
2343 if (cmValue c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
2344 tool = "Content";
2345 copyToOutDir = *c;
2346 toolHasSettings = true;
2348 if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
2349 includeInVsix = "True";
2350 tool = "Content";
2351 toolHasSettings = true;
2354 // Collect VS_CSHARP_* property values (if some are set)
2355 std::map<std::string, std::string> sourceFileTags;
2356 this->GetCSharpSourceProperties(sf, sourceFileTags);
2358 if (this->NsightTegra) {
2359 // Nsight Tegra needs specific file types to check up-to-dateness.
2360 std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
2361 if (name == "androidmanifest.xml"_s || name == "build.xml"_s ||
2362 name == "proguard.cfg"_s || name == "proguard-project.txt"_s ||
2363 ext == "properties"_s) {
2364 tool = "AndroidBuild";
2365 } else if (ext == "java"_s) {
2366 tool = "JCompile";
2367 } else if (ext == "asm"_s || ext == "s"_s) {
2368 tool = "ClCompile";
2372 cmValue toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
2373 if (cmNonempty(toolOverride)) {
2374 tool = toolOverride->c_str();
2377 std::string deployContent;
2378 std::string deployLocation;
2379 if (this->GlobalGenerator->TargetsWindowsPhone() ||
2380 this->GlobalGenerator->TargetsWindowsStore()) {
2381 cmValue content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
2382 if (cmNonempty(content)) {
2383 toolHasSettings = true;
2384 deployContent = *content;
2386 cmValue location = sf->GetProperty("VS_DEPLOYMENT_LOCATION");
2387 if (cmNonempty(location)) {
2388 deployLocation = *location;
2393 if (ParsedToolTargetSettings.find(tool) == ParsedToolTargetSettings.end()) {
2394 cmValue toolTargetProperty = this->GeneratorTarget->Target->GetProperty(
2395 cmStrCat("VS_SOURCE_SETTINGS_", tool));
2396 ConfigToSettings toolTargetSettings;
2397 if (toolTargetProperty) {
2398 ParseSettingsProperty(*toolTargetProperty, toolTargetSettings);
2401 ParsedToolTargetSettings[tool] = toolTargetSettings;
2404 for (const auto& configToSetting : ParsedToolTargetSettings[tool]) {
2405 for (const auto& setting : configToSetting.second) {
2406 toolSettings[configToSetting.first][setting.first] = setting.second;
2410 if (!toolSettings.empty()) {
2411 toolHasSettings = true;
2414 Elem e2(e1, tool);
2415 this->WriteSource(e2, sf);
2416 if (toolHasSettings) {
2417 e2.SetHasElements();
2419 this->FinishWritingSource(e2, toolSettings);
2421 if (!deployContent.empty()) {
2422 cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
2423 std::unique_ptr<cmCompiledGeneratorExpression> cge =
2424 ge.Parse(deployContent);
2425 // Deployment location cannot be set on a configuration basis
2426 if (!deployLocation.empty()) {
2427 e2.Element("Link",
2428 cmStrCat(deployLocation, "\\%(FileName)%(Extension)"));
2430 for (auto& config : this->Configurations) {
2431 if (cge->Evaluate(this->LocalGenerator, config) == "1"_s) {
2432 e2.WritePlatformConfigTag(
2433 "DeploymentContent",
2434 cmStrCat("'$(Configuration)|$(Platform)'=='", config, '|',
2435 this->Platform, '\''),
2436 "true");
2437 } else {
2438 e2.WritePlatformConfigTag(
2439 "ExcludedFromBuild",
2440 cmStrCat("'$(Configuration)|$(Platform)'=='", config, '|',
2441 this->Platform, '\''),
2442 "true");
2447 if (!settingsGenerator.empty()) {
2448 e2.Element("Generator", settingsGenerator);
2450 if (!settingsLastGenOutput.empty()) {
2451 e2.Element("LastGenOutput", settingsLastGenOutput);
2453 if (!subType.empty()) {
2454 e2.Element("SubType", subType);
2456 if (!copyToOutDir.empty()) {
2457 e2.Element("CopyToOutputDirectory", copyToOutDir);
2459 if (!includeInVsix.empty()) {
2460 e2.Element("IncludeInVSIX", includeInVsix);
2462 // write source file specific tags
2463 this->WriteCSharpSourceProperties(e2, sourceFileTags);
2467 void cmVisualStudio10TargetGenerator::WriteSource(Elem& e2,
2468 cmSourceFile const* sf)
2470 // Visual Studio tools append relative paths to the current dir, as in:
2472 // c:\path\to\current\dir\..\..\..\relative\path\to\source.c
2474 // and fail if this exceeds the maximum allowed path length. Our path
2475 // conversion uses full paths when possible to allow deeper trees.
2476 // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
2477 // we must use relative paths.
2478 bool forceRelative = sf->GetLanguage() == "CUDA"_s;
2479 std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative);
2480 ConvertToWindowsSlash(sourceFile);
2481 e2.Attribute("Include", sourceFile);
2483 if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
2484 // For out of source projects we have to provide a link (if not specified
2485 // via property) for every source file (besides .cs files) otherwise they
2486 // will not be visible in VS at all.
2487 // First we check if the file is in a source group, then we check if the
2488 // file path is relative to current source- or binary-dir, otherwise it is
2489 // added with the plain filename without any path. This means the file will
2490 // show up at root-level of the csproj (where CMakeLists.txt etc. are).
2491 std::string link = this->GetCSharpSourceLink(sf);
2492 if (link.empty()) {
2493 link = cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
2495 e2.Element("Link", link);
2498 ToolSource toolSource = { sf, forceRelative };
2499 this->Tools[e2.Tag].push_back(toolSource);
2502 void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
2504 if (this->GeneratorTarget->GetType() == cmStateEnums::GLOBAL_TARGET) {
2505 return;
2508 const bool haveUnityBuild =
2509 this->GeneratorTarget->GetPropertyAsBool("UNITY_BUILD");
2511 if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
2512 Elem e1(e0, "PropertyGroup");
2513 e1.Element("EnableUnitySupport", "true");
2516 Elem e1(e0, "ItemGroup");
2517 e1.SetHasElements();
2519 std::vector<size_t> all_configs;
2520 for (size_t ci = 0; ci < this->Configurations.size(); ++ci) {
2521 all_configs.push_back(ci);
2524 std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
2525 this->GeneratorTarget->GetAllConfigSources();
2527 cmSourceFile const* srcCMakeLists =
2528 this->LocalGenerator->CreateVCProjBuildRule();
2530 for (cmGeneratorTarget::AllConfigSource const& si : sources) {
2531 if (si.Source == srcCMakeLists) {
2532 // Skip explicit reference to CMakeLists.txt source.
2533 continue;
2536 ConfigToSettings toolSettings;
2537 for (const auto& config : this->Configurations) {
2538 toolSettings[config];
2540 if (cmValue p = si.Source->GetProperty("VS_SETTINGS")) {
2541 ParseSettingsProperty(*p, toolSettings);
2544 const char* tool = nullptr;
2545 switch (si.Kind) {
2546 case cmGeneratorTarget::SourceKindAppManifest:
2547 tool = "AppxManifest";
2548 break;
2549 case cmGeneratorTarget::SourceKindCertificate:
2550 tool = "None";
2551 break;
2552 case cmGeneratorTarget::SourceKindCustomCommand:
2553 // Handled elsewhere.
2554 break;
2555 case cmGeneratorTarget::SourceKindExternalObject:
2556 tool = "Object";
2557 break;
2558 case cmGeneratorTarget::SourceKindExtra:
2559 this->WriteExtraSource(e1, si.Source, toolSettings);
2560 break;
2561 case cmGeneratorTarget::SourceKindHeader:
2562 this->WriteHeaderSource(e1, si.Source, toolSettings);
2563 break;
2564 case cmGeneratorTarget::SourceKindIDL:
2565 tool = "Midl";
2566 break;
2567 case cmGeneratorTarget::SourceKindManifest:
2568 // Handled elsewhere.
2569 break;
2570 case cmGeneratorTarget::SourceKindModuleDefinition:
2571 tool = "None";
2572 break;
2573 case cmGeneratorTarget::SourceKindCxxModuleSource:
2574 case cmGeneratorTarget::SourceKindUnityBatched:
2575 case cmGeneratorTarget::SourceKindObjectSource: {
2576 const std::string& lang = si.Source->GetLanguage();
2577 if (lang == "C"_s || lang == "CXX"_s) {
2578 tool = "ClCompile";
2579 } else if (lang == "ASM_MARMASM"_s &&
2580 this->GlobalGenerator->IsMarmasmEnabled()) {
2581 tool = "MARMASM";
2582 } else if (lang == "ASM_MASM"_s &&
2583 this->GlobalGenerator->IsMasmEnabled()) {
2584 tool = "MASM";
2585 } else if (lang == "ASM_NASM"_s &&
2586 this->GlobalGenerator->IsNasmEnabled()) {
2587 tool = "NASM";
2588 } else if (lang == "RC"_s) {
2589 tool = "ResourceCompile";
2590 } else if (lang == "CSharp"_s) {
2591 tool = "Compile";
2592 } else if (lang == "CUDA"_s &&
2593 this->GlobalGenerator->IsCudaEnabled()) {
2594 tool = "CudaCompile";
2595 } else {
2596 tool = "None";
2598 } break;
2599 case cmGeneratorTarget::SourceKindResx:
2600 this->ResxObjs.push_back(si.Source);
2601 break;
2602 case cmGeneratorTarget::SourceKindXaml:
2603 this->XamlObjs.push_back(si.Source);
2604 break;
2607 std::string config;
2608 if (!this->Configurations.empty()) {
2609 config = this->Configurations[si.Configs[0]];
2611 auto const* fs =
2612 this->GeneratorTarget->GetFileSetForSource(config, si.Source);
2613 if (tool) {
2614 // Compute set of configurations to exclude, if any.
2615 std::vector<size_t> const& include_configs = si.Configs;
2616 std::vector<size_t> exclude_configs;
2617 std::set_difference(all_configs.begin(), all_configs.end(),
2618 include_configs.begin(), include_configs.end(),
2619 std::back_inserter(exclude_configs));
2621 Elem e2(e1, tool);
2622 bool isCSharp = (si.Source->GetLanguage() == "CSharp"_s);
2623 if (isCSharp && !exclude_configs.empty()) {
2624 std::stringstream conditions;
2625 bool firstConditionSet{ false };
2626 for (const auto& ci : include_configs) {
2627 if (firstConditionSet) {
2628 conditions << " Or ";
2630 conditions << "('$(Configuration)|$(Platform)'=='"
2631 << this->Configurations[ci] << '|' << this->Platform
2632 << "')";
2633 firstConditionSet = true;
2635 e2.Attribute("Condition", conditions.str());
2637 this->WriteSource(e2, si.Source);
2639 bool useNativeUnityBuild = false;
2640 if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
2641 // Magic value taken from cmGlobalVisualStudioVersionedGenerator.cxx
2642 static const std::string vs15 = "141";
2643 std::string toolset =
2644 this->GlobalGenerator->GetPlatformToolsetString();
2645 cmSystemTools::ReplaceString(toolset, "v", "");
2647 if (toolset.empty() ||
2648 cmSystemTools::VersionCompareGreaterEq(toolset, vs15)) {
2649 useNativeUnityBuild = true;
2653 if (haveUnityBuild && strcmp(tool, "ClCompile") == 0 &&
2654 si.Source->GetProperty("UNITY_SOURCE_FILE")) {
2655 if (useNativeUnityBuild) {
2656 e2.Attribute(
2657 "IncludeInUnityFile",
2658 si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")
2659 ? "false"
2660 : "true");
2661 e2.Attribute("CustomUnityFile", "true");
2663 std::string unityDir = cmSystemTools::GetFilenamePath(
2664 *si.Source->GetProperty("UNITY_SOURCE_FILE"));
2665 e2.Attribute("UnityFilesDirectory", unityDir);
2666 } else {
2667 // Visual Studio versions prior to 2017 15.8 do not know about unity
2668 // builds, thus we exclude the files already part of unity sources.
2669 if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
2670 exclude_configs = all_configs;
2674 if (haveUnityBuild && strcmp(tool, "CudaCompile") == 0 &&
2675 si.Source->GetProperty("UNITY_SOURCE_FILE")) {
2676 if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
2677 exclude_configs = all_configs;
2681 if (si.Kind == cmGeneratorTarget::SourceKindObjectSource ||
2682 si.Kind == cmGeneratorTarget::SourceKindUnityBatched) {
2683 this->OutputSourceSpecificFlags(e2, si.Source);
2684 } else if (fs && fs->GetType() == "CXX_MODULES"_s) {
2685 this->GeneratorTarget->Makefile->IssueMessage(
2686 MessageType::FATAL_ERROR,
2687 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
2688 "\" has source file\n ", si.Source->GetFullPath(),
2689 "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
2690 "scheduled for compilation."));
2692 if (si.Source->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
2693 e2.Element("PrecompiledHeader", "NotUsing");
2695 if (!isCSharp && !exclude_configs.empty()) {
2696 this->WriteExcludeFromBuild(e2, exclude_configs);
2699 this->FinishWritingSource(e2, toolSettings);
2700 } else if (fs && fs->GetType() == "CXX_MODULES"_s) {
2701 this->GeneratorTarget->Makefile->IssueMessage(
2702 MessageType::FATAL_ERROR,
2703 cmStrCat("Target \"", this->GeneratorTarget->GetName(),
2704 "\" has source file\n ", si.Source->GetFullPath(),
2705 "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
2706 "scheduled for compilation."));
2710 if (this->IsMissingFiles) {
2711 this->WriteMissingFiles(e1);
2715 void cmVisualStudio10TargetGenerator::FinishWritingSource(
2716 Elem& e2, ConfigToSettings const& toolSettings)
2718 std::vector<std::string> writtenSettings;
2719 for (const auto& configSettings : toolSettings) {
2720 for (const auto& setting : configSettings.second) {
2722 if (std::find(writtenSettings.begin(), writtenSettings.end(),
2723 setting.first) != writtenSettings.end()) {
2724 continue;
2727 if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
2728 e2.Element(setting.first, setting.second);
2729 writtenSettings.push_back(setting.first);
2730 } else {
2731 e2.WritePlatformConfigTag(setting.first,
2732 cmStrCat("'$(Configuration)|$(Platform)'=='",
2733 configSettings.first, '|',
2734 this->Platform, '\''),
2735 setting.second);
2741 void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
2742 Elem& e2, cmSourceFile const* source)
2744 cmSourceFile const& sf = *source;
2746 std::string objectName;
2747 if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
2748 objectName = this->GeneratorTarget->GetObjectName(&sf);
2750 std::string flags;
2751 bool configDependentFlags = false;
2752 std::string options;
2753 bool configDependentOptions = false;
2754 std::string defines;
2755 bool configDependentDefines = false;
2756 std::string includes;
2757 bool configDependentIncludes = false;
2758 if (cmValue cflags = sf.GetProperty("COMPILE_FLAGS")) {
2759 configDependentFlags =
2760 cmGeneratorExpression::Find(*cflags) != std::string::npos;
2761 flags += *cflags;
2763 if (cmValue coptions = sf.GetProperty("COMPILE_OPTIONS")) {
2764 configDependentOptions =
2765 cmGeneratorExpression::Find(*coptions) != std::string::npos;
2766 options += *coptions;
2768 if (cmValue cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
2769 configDependentDefines =
2770 cmGeneratorExpression::Find(*cdefs) != std::string::npos;
2771 defines += *cdefs;
2773 if (cmValue cincludes = sf.GetProperty("INCLUDE_DIRECTORIES")) {
2774 configDependentIncludes =
2775 cmGeneratorExpression::Find(*cincludes) != std::string::npos;
2776 includes += *cincludes;
2779 // Force language if the file extension does not match.
2780 // Note that MSVC treats the upper-case '.C' extension as C and not C++.
2781 std::string const ext = sf.GetExtension();
2782 std::string const extLang = ext == "C"_s
2783 ? "C"
2784 : this->GlobalGenerator->GetLanguageFromExtension(ext.c_str());
2785 std::string lang = this->LocalGenerator->GetSourceFileLanguage(sf);
2786 const char* compileAs = nullptr;
2787 if (lang != extLang) {
2788 if (lang == "CXX"_s) {
2789 // force a C++ file type
2790 compileAs = "CompileAsCpp";
2791 } else if (lang == "C"_s) {
2792 // force to c
2793 compileAs = "CompileAsC";
2797 bool noWinRT = this->TargetCompileAsWinRT && lang == "C"_s;
2798 // for the first time we need a new line if there is something
2799 // produced here.
2800 if (!objectName.empty()) {
2801 if (lang == "CUDA"_s) {
2802 e2.Element("CompileOut", cmStrCat("$(IntDir)/", objectName));
2803 } else {
2804 e2.Element("ObjectFileName", cmStrCat("$(IntDir)/", objectName));
2808 if (lang == "ASM_NASM"_s) {
2809 if (cmValue objectDeps = sf.GetProperty("OBJECT_DEPENDS")) {
2810 cmList depends{ *objectDeps };
2811 for (auto& d : depends) {
2812 ConvertToWindowsSlash(d);
2814 e2.Element("AdditionalDependencies", depends.join(";"));
2818 bool isCppModule = false;
2820 for (std::string const& config : this->Configurations) {
2821 this->GeneratorTarget->NeedCxxModuleSupport(lang, config);
2823 std::string configUpper = cmSystemTools::UpperCase(config);
2824 std::string configDefines = defines;
2825 std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
2826 if (cmValue ccdefs = sf.GetProperty(defPropName)) {
2827 if (!configDefines.empty()) {
2828 configDefines += ';';
2830 configDependentDefines |=
2831 cmGeneratorExpression::Find(*ccdefs) != std::string::npos;
2832 configDefines += *ccdefs;
2835 bool const shouldScanForModules = lang == "CXX"_s &&
2836 this->GeneratorTarget->NeedDyndepForSource(lang, config, source);
2837 auto const* fs =
2838 this->GeneratorTarget->GetFileSetForSource(config, source);
2839 const char* compileAsPerConfig = compileAs;
2840 if (fs && fs->GetType() == "CXX_MODULES"_s) {
2841 if (lang == "CXX"_s) {
2842 if (fs->GetType() == "CXX_MODULES"_s) {
2843 isCppModule = true;
2844 if (shouldScanForModules &&
2845 this->GlobalGenerator->IsScanDependenciesSupported()) {
2846 // ScanSourceForModuleDependencies uses 'cl /scanDependencies' and
2847 // can distinguish module interface units and internal partitions.
2848 compileAsPerConfig = "CompileAsCpp";
2849 } else {
2850 compileAsPerConfig = "CompileAsCppModule";
2852 } else {
2853 compileAsPerConfig = "CompileAsHeaderUnit";
2855 } else {
2856 this->Makefile->IssueMessage(
2857 MessageType::FATAL_ERROR,
2858 cmStrCat(
2859 "Target \"", this->GeneratorTarget->Target->GetName(),
2860 "\" contains the source\n ", source->GetFullPath(),
2861 "\nin a file set of type \"", fs->GetType(),
2862 R"(" but the source is not classified as a "CXX" source.)"));
2866 // We have pch state in the following situation:
2867 // 1. We have SKIP_PRECOMPILE_HEADERS == true
2868 // 2. We are creating the pre-compiled header
2869 // 3. We are a different language than the linker language AND pch is
2870 // enabled.
2871 std::string const& linkLanguage =
2872 this->GeneratorTarget->GetLinkerLanguage(config);
2873 std::string const& pchSource =
2874 this->GeneratorTarget->GetPchSource(config, lang);
2875 const bool skipPCH =
2876 pchSource.empty() || sf.GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS");
2877 const bool makePCH = (sf.GetFullPath() == pchSource);
2878 const bool useSharedPCH = !skipPCH && (lang == linkLanguage);
2879 const bool useDifferentLangPCH = !skipPCH && (lang != linkLanguage);
2880 const bool useNoPCH = skipPCH && (lang != linkLanguage) &&
2881 !this->GeneratorTarget->GetPchHeader(config, linkLanguage).empty();
2882 const bool needsPCHFlags =
2883 (makePCH || useSharedPCH || useDifferentLangPCH || useNoPCH);
2885 // if we have flags or defines for this config then
2886 // use them
2887 if (!flags.empty() || !options.empty() || !configDefines.empty() ||
2888 !includes.empty() || compileAsPerConfig || noWinRT ||
2889 !options.empty() || needsPCHFlags ||
2890 (shouldScanForModules !=
2891 this->ScanSourceForModuleDependencies[config])) {
2892 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
2893 cmIDEFlagTable const* flagtable = nullptr;
2894 const std::string& srclang = source->GetLanguage();
2895 if (srclang == "C"_s || srclang == "CXX"_s) {
2896 flagtable = gg->GetClFlagTable();
2897 } else if (srclang == "ASM_MARMASM"_s &&
2898 this->GlobalGenerator->IsMarmasmEnabled()) {
2899 flagtable = gg->GetMarmasmFlagTable();
2900 } else if (srclang == "ASM_MASM"_s &&
2901 this->GlobalGenerator->IsMasmEnabled()) {
2902 flagtable = gg->GetMasmFlagTable();
2903 } else if (lang == "ASM_NASM"_s &&
2904 this->GlobalGenerator->IsNasmEnabled()) {
2905 flagtable = gg->GetNasmFlagTable();
2906 } else if (srclang == "RC"_s) {
2907 flagtable = gg->GetRcFlagTable();
2908 } else if (srclang == "CSharp"_s) {
2909 flagtable = gg->GetCSharpFlagTable();
2911 cmGeneratorExpressionInterpreter genexInterpreter(
2912 this->LocalGenerator, config, this->GeneratorTarget, lang);
2913 cmVS10GeneratorOptions clOptions(
2914 this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
2915 flagtable, this);
2916 if (compileAsPerConfig) {
2917 clOptions.AddFlag("CompileAs", compileAsPerConfig);
2919 if (shouldScanForModules !=
2920 this->ScanSourceForModuleDependencies[config]) {
2921 clOptions.AddFlag("ScanSourceForModuleDependencies",
2922 shouldScanForModules ? "true" : "false");
2924 if (noWinRT) {
2925 clOptions.AddFlag("CompileAsWinRT", "false");
2927 if (configDependentFlags) {
2928 clOptions.Parse(genexInterpreter.Evaluate(flags, "COMPILE_FLAGS"));
2929 } else {
2930 clOptions.Parse(flags);
2933 if (needsPCHFlags) {
2934 // Add precompile headers compile options.
2935 if (makePCH) {
2936 clOptions.AddFlag("PrecompiledHeader", "Create");
2937 std::string pchHeader =
2938 this->GeneratorTarget->GetPchHeader(config, lang);
2939 clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
2940 std::string pchFile =
2941 this->GeneratorTarget->GetPchFile(config, lang);
2942 clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
2943 clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2944 } else if (useNoPCH) {
2945 clOptions.AddFlag("PrecompiledHeader", "NotUsing");
2946 } else if (useSharedPCH) {
2947 std::string pchHeader =
2948 this->GeneratorTarget->GetPchHeader(config, lang);
2949 clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2950 } else if (useDifferentLangPCH) {
2951 clOptions.AddFlag("PrecompiledHeader", "Use");
2952 std::string pchHeader =
2953 this->GeneratorTarget->GetPchHeader(config, lang);
2954 clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
2955 std::string pchFile =
2956 this->GeneratorTarget->GetPchFile(config, lang);
2957 clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
2958 clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2962 if (!options.empty()) {
2963 std::string expandedOptions;
2964 if (configDependentOptions) {
2965 this->LocalGenerator->AppendCompileOptions(
2966 expandedOptions,
2967 genexInterpreter.Evaluate(options, "COMPILE_OPTIONS"));
2968 } else {
2969 this->LocalGenerator->AppendCompileOptions(expandedOptions, options);
2971 clOptions.Parse(expandedOptions);
2973 if (clOptions.HasFlag("DisableSpecificWarnings")) {
2974 clOptions.AppendFlag("DisableSpecificWarnings",
2975 "%(DisableSpecificWarnings)");
2977 if (clOptions.HasFlag("ForcedIncludeFiles")) {
2978 clOptions.AppendFlag("ForcedIncludeFiles", "%(ForcedIncludeFiles)");
2980 if (configDependentDefines) {
2981 clOptions.AddDefines(
2982 genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS"));
2983 } else {
2984 clOptions.AddDefines(configDefines);
2986 std::vector<std::string> includeList;
2987 if (configDependentIncludes) {
2988 this->LocalGenerator->AppendIncludeDirectories(
2989 includeList,
2990 genexInterpreter.Evaluate(includes, "INCLUDE_DIRECTORIES"), *source);
2991 } else {
2992 this->LocalGenerator->AppendIncludeDirectories(includeList, includes,
2993 *source);
2995 clOptions.AddIncludes(includeList);
2996 clOptions.SetConfiguration(config);
2997 OptionsHelper oh(clOptions, e2);
2998 oh.PrependInheritedString("AdditionalOptions");
2999 oh.OutputAdditionalIncludeDirectories(lang);
3000 oh.OutputFlagMap();
3001 oh.OutputPreprocessorDefinitions(lang);
3005 if (isCppModule && !objectName.empty()) {
3006 std::string baseName = cmStrCat("$(IntDir)/", objectName);
3007 cmStripSuffixIfExists(baseName, ".obj");
3008 e2.Element("ModuleOutputFile", cmStrCat(baseName, ".ifc"));
3009 e2.Element("ModuleDependenciesFile", cmStrCat(baseName, ".module.json"));
3012 if (this->IsXamlSource(source->GetFullPath())) {
3013 const std::string& fileName = source->GetFullPath();
3014 e2.Element("DependentUpon",
3015 fileName.substr(0, fileName.find_last_of('.')));
3017 if (this->ProjectType == VsProjectType::csproj) {
3018 using CsPropMap = std::map<std::string, std::string>;
3019 CsPropMap sourceFileTags;
3020 this->GetCSharpSourceProperties(&sf, sourceFileTags);
3021 // write source file specific tags
3022 if (!sourceFileTags.empty()) {
3023 this->WriteCSharpSourceProperties(e2, sourceFileTags);
3028 void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild(
3029 Elem& e2, std::vector<size_t> const& exclude_configs)
3031 for (size_t ci : exclude_configs) {
3032 e2.WritePlatformConfigTag("ExcludedFromBuild",
3033 cmStrCat("'$(Configuration)|$(Platform)'=='",
3034 this->Configurations[ci], '|',
3035 this->Platform, '\''),
3036 "true");
3040 void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions(
3041 Elem& e0)
3043 cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
3044 if (ttype > cmStateEnums::INTERFACE_LIBRARY) {
3045 return;
3047 if (this->ProjectType == VsProjectType::csproj) {
3048 return;
3051 Elem e1(e0, "PropertyGroup");
3052 e1.Element("_ProjectFileVersion", "10.0.20506.1");
3053 for (std::string const& config : this->Configurations) {
3054 const std::string cond = this->CalcCondition(config);
3056 if (ttype >= cmStateEnums::UTILITY) {
3057 e1.WritePlatformConfigTag(
3058 "IntDir", cond, R"($(Platform)\$(Configuration)\$(ProjectName)\)");
3059 } else {
3060 if (ttype == cmStateEnums::SHARED_LIBRARY ||
3061 ttype == cmStateEnums::MODULE_LIBRARY ||
3062 ttype == cmStateEnums::EXECUTABLE) {
3063 auto linker = this->GeneratorTarget->GetLinkerTool(config);
3064 if (!linker.empty()) {
3065 ConvertToWindowsSlash(linker);
3066 e1.WritePlatformConfigTag("LinkToolExe", cond, linker);
3070 std::string intermediateDir = cmStrCat(
3071 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/',
3072 config, '/');
3073 std::string outDir;
3074 std::string targetNameFull;
3075 if (ttype == cmStateEnums::OBJECT_LIBRARY) {
3076 outDir = intermediateDir;
3077 targetNameFull = cmStrCat(this->GeneratorTarget->GetName(), ".lib");
3078 } else {
3079 outDir = cmStrCat(this->GeneratorTarget->GetDirectory(config), '/');
3080 targetNameFull = this->GeneratorTarget->GetFullName(config);
3082 ConvertToWindowsSlash(intermediateDir);
3083 ConvertToWindowsSlash(outDir);
3085 e1.WritePlatformConfigTag("OutDir", cond, outDir);
3087 e1.WritePlatformConfigTag("IntDir", cond, intermediateDir);
3089 if (cmValue sdkExecutableDirectories = this->Makefile->GetDefinition(
3090 "CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES")) {
3091 e1.WritePlatformConfigTag("ExecutablePath", cond,
3092 *sdkExecutableDirectories);
3095 if (cmValue sdkIncludeDirectories = this->Makefile->GetDefinition(
3096 "CMAKE_VS_SDK_INCLUDE_DIRECTORIES")) {
3097 e1.WritePlatformConfigTag("IncludePath", cond, *sdkIncludeDirectories);
3100 if (cmValue sdkReferenceDirectories = this->Makefile->GetDefinition(
3101 "CMAKE_VS_SDK_REFERENCE_DIRECTORIES")) {
3102 e1.WritePlatformConfigTag("ReferencePath", cond,
3103 *sdkReferenceDirectories);
3106 if (cmValue sdkLibraryDirectories = this->Makefile->GetDefinition(
3107 "CMAKE_VS_SDK_LIBRARY_DIRECTORIES")) {
3108 e1.WritePlatformConfigTag("LibraryPath", cond, *sdkLibraryDirectories);
3111 if (cmValue sdkLibraryWDirectories = this->Makefile->GetDefinition(
3112 "CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES")) {
3113 e1.WritePlatformConfigTag("LibraryWPath", cond,
3114 *sdkLibraryWDirectories);
3117 if (cmValue sdkSourceDirectories =
3118 this->Makefile->GetDefinition("CMAKE_VS_SDK_SOURCE_DIRECTORIES")) {
3119 e1.WritePlatformConfigTag("SourcePath", cond, *sdkSourceDirectories);
3122 if (cmValue sdkExcludeDirectories = this->Makefile->GetDefinition(
3123 "CMAKE_VS_SDK_EXCLUDE_DIRECTORIES")) {
3124 e1.WritePlatformConfigTag("ExcludePath", cond, *sdkExcludeDirectories);
3127 std::string name =
3128 cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
3129 e1.WritePlatformConfigTag("TargetName", cond, name);
3131 std::string ext =
3132 cmSystemTools::GetFilenameLastExtension(targetNameFull);
3133 if (ext.empty()) {
3134 // An empty TargetExt causes a default extension to be used.
3135 // A single "." appears to be treated as an empty extension.
3136 ext = ".";
3138 e1.WritePlatformConfigTag("TargetExt", cond, ext);
3140 this->OutputLinkIncremental(e1, config);
3143 if (ttype <= cmStateEnums::UTILITY) {
3144 if (cmValue workingDir = this->GeneratorTarget->GetProperty(
3145 "VS_DEBUGGER_WORKING_DIRECTORY")) {
3146 std::string genWorkingDir = cmGeneratorExpression::Evaluate(
3147 *workingDir, this->LocalGenerator, config);
3148 e1.WritePlatformConfigTag("LocalDebuggerWorkingDirectory", cond,
3149 genWorkingDir);
3152 if (cmValue environment =
3153 this->GeneratorTarget->GetProperty("VS_DEBUGGER_ENVIRONMENT")) {
3154 std::string genEnvironment = cmGeneratorExpression::Evaluate(
3155 *environment, this->LocalGenerator, config);
3156 e1.WritePlatformConfigTag("LocalDebuggerEnvironment", cond,
3157 genEnvironment);
3160 if (cmValue debuggerCommand =
3161 this->GeneratorTarget->GetProperty("VS_DEBUGGER_COMMAND")) {
3162 std::string genDebuggerCommand = cmGeneratorExpression::Evaluate(
3163 *debuggerCommand, this->LocalGenerator, config);
3164 e1.WritePlatformConfigTag("LocalDebuggerCommand", cond,
3165 genDebuggerCommand);
3168 if (cmValue commandArguments = this->GeneratorTarget->GetProperty(
3169 "VS_DEBUGGER_COMMAND_ARGUMENTS")) {
3170 std::string genCommandArguments = cmGeneratorExpression::Evaluate(
3171 *commandArguments, this->LocalGenerator, config);
3172 e1.WritePlatformConfigTag("LocalDebuggerCommandArguments", cond,
3173 genCommandArguments);
3179 void cmVisualStudio10TargetGenerator::WritePublicProjectContentOptions(
3180 Elem& e0)
3182 cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
3183 if (ttype != cmStateEnums::SHARED_LIBRARY) {
3184 return;
3186 if (this->ProjectType != VsProjectType::vcxproj) {
3187 return;
3190 Elem e1(e0, "PropertyGroup");
3191 for (std::string const& config : this->Configurations) {
3192 if (this->GeneratorTarget->HaveCxx20ModuleSources() &&
3193 this->GeneratorTarget->HaveCxxModuleSupport(config) ==
3194 cmGeneratorTarget::Cxx20SupportLevel::Supported) {
3195 const std::string cond = this->CalcCondition(config);
3196 // For DLL projects, we export all BMIs for now
3197 e1.WritePlatformConfigTag("AllProjectBMIsArePublic", cond, "true");
3202 void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
3203 Elem& e1, std::string const& configName)
3205 if (!this->MSTools) {
3206 return;
3208 if (this->ProjectType == VsProjectType::csproj) {
3209 return;
3211 // static libraries and things greater than modules do not need
3212 // to set this option
3213 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
3214 this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
3215 return;
3217 Options& linkOptions = *(this->LinkOptions[configName]);
3218 const std::string cond = this->CalcCondition(configName);
3220 if (this->IPOEnabledConfigurations.count(configName) > 0) {
3221 // Suppress LinkIncremental in favor of WholeProgramOptimization.
3222 e1.WritePlatformConfigTag("LinkIncremental", cond, "");
3223 } else {
3224 const char* incremental = linkOptions.GetFlag("LinkIncremental");
3225 e1.WritePlatformConfigTag("LinkIncremental", cond,
3226 (incremental ? incremental : "true"));
3228 linkOptions.RemoveFlag("LinkIncremental");
3230 const char* manifest = linkOptions.GetFlag("GenerateManifest");
3231 e1.WritePlatformConfigTag("GenerateManifest", cond,
3232 (manifest ? manifest : "true"));
3233 linkOptions.RemoveFlag("GenerateManifest");
3235 // Some link options belong here. Use them now and remove them so that
3236 // WriteLinkOptions does not use them.
3237 static const std::vector<std::string> flags{ "LinkDelaySign",
3238 "LinkKeyFile" };
3239 for (const std::string& flag : flags) {
3240 if (const char* value = linkOptions.GetFlag(flag)) {
3241 e1.WritePlatformConfigTag(flag, cond, value);
3242 linkOptions.RemoveFlag(flag);
3247 std::vector<std::string> cmVisualStudio10TargetGenerator::GetIncludes(
3248 std::string const& config, std::string const& lang) const
3250 std::vector<std::string> includes;
3251 this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
3252 lang, config);
3253 for (std::string& i : includes) {
3254 ConvertToWindowsSlash(i);
3256 return includes;
3259 std::string cmVisualStudio10TargetGenerator::GetTargetOutputName() const
3261 std::string config;
3262 if (!this->Configurations.empty()) {
3263 config = this->Configurations[0];
3265 const auto& nameComponents =
3266 this->GeneratorTarget->GetFullNameComponents(config);
3267 return cmStrCat(nameComponents.prefix, nameComponents.base);
3270 std::string cmVisualStudio10TargetGenerator::GetAssemblyName(
3271 std::string const& config) const
3273 std::string postfixName =
3274 cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
3275 std::string assemblyName = this->GeneratorTarget->GetOutputName(
3276 config, cmStateEnums::RuntimeBinaryArtifact);
3277 if (cmValue postfix = this->GeneratorTarget->GetProperty(postfixName)) {
3278 assemblyName += *postfix;
3280 return assemblyName;
3283 bool cmVisualStudio10TargetGenerator::ComputeClOptions()
3285 return std::all_of(
3286 this->Configurations.begin(), this->Configurations.end(),
3287 [this](std::string const& c) { return this->ComputeClOptions(c); });
3290 bool cmVisualStudio10TargetGenerator::ComputeClOptions(
3291 std::string const& configName)
3293 // much of this was copied from here:
3294 // copied from cmLocalVisualStudio7Generator.cxx 805
3295 // TODO: Integrate code below with cmLocalVisualStudio7Generator.
3297 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3298 std::unique_ptr<Options> pOptions;
3299 switch (this->ProjectType) {
3300 case VsProjectType::vcxproj:
3301 pOptions = cm::make_unique<Options>(
3302 this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
3303 break;
3304 case VsProjectType::csproj:
3305 pOptions =
3306 cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
3307 gg->GetCSharpFlagTable());
3308 break;
3309 default:
3310 break;
3312 Options& clOptions = *pOptions;
3314 std::string flags;
3315 const std::string& linkLanguage =
3316 this->GeneratorTarget->GetLinkerLanguage(configName);
3317 if (linkLanguage.empty()) {
3318 cmSystemTools::Error(cmStrCat(
3319 "CMake can not determine linker language for target: ", this->Name));
3320 return false;
3323 // Choose a language whose flags to use for ClCompile.
3324 static const char* clLangs[] = { "CXX", "C", "Fortran" };
3325 std::string langForClCompile;
3326 if (this->ProjectType == VsProjectType::csproj) {
3327 langForClCompile = "CSharp";
3328 } else if (cm::contains(clLangs, linkLanguage)) {
3329 langForClCompile = linkLanguage;
3330 } else {
3331 std::set<std::string> languages;
3332 this->GeneratorTarget->GetLanguages(languages, configName);
3333 for (const char* l : clLangs) {
3334 if (languages.count(l)) {
3335 langForClCompile = l;
3336 break;
3340 this->LangForClCompile = langForClCompile;
3341 if (!langForClCompile.empty()) {
3342 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3343 cmBuildStep::Compile,
3344 langForClCompile, configName);
3345 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
3346 langForClCompile, configName);
3349 // Put the IPO enabled configurations into a set.
3350 if (this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName)) {
3351 this->IPOEnabledConfigurations.insert(configName);
3354 // Check if ASan is enabled.
3355 if (flags.find("/fsanitize=address") != std::string::npos ||
3356 flags.find("-fsanitize=address") != std::string::npos) {
3357 this->ASanEnabledConfigurations.insert(configName);
3360 // Check if (lib)Fuzzer is enabled.
3361 if (flags.find("/fsanitize=fuzzer") != std::string::npos ||
3362 flags.find("-fsanitize=fuzzer") != std::string::npos) {
3363 this->FuzzerEnabledConfigurations.insert(configName);
3366 // Precompile Headers
3367 std::string pchHeader =
3368 this->GeneratorTarget->GetPchHeader(configName, linkLanguage);
3369 if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
3370 pchHeader.empty()) {
3371 clOptions.AddFlag("PrecompiledHeader", "NotUsing");
3372 } else if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
3373 !pchHeader.empty()) {
3374 clOptions.AddFlag("PrecompiledHeader", "Use");
3375 clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
3376 std::string pchFile =
3377 this->GeneratorTarget->GetPchFile(configName, linkLanguage);
3378 clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
3381 // Get preprocessor definitions for this directory.
3382 std::string defineFlags = this->Makefile->GetDefineFlags();
3383 if (this->MSTools) {
3384 if (this->ProjectType == VsProjectType::vcxproj) {
3385 clOptions.FixExceptionHandlingDefault();
3386 if (this->GlobalGenerator->GetVersion() >=
3387 cmGlobalVisualStudioGenerator::VSVersion::VS15) {
3388 // Toolsets that come with VS 2017 may now enable UseFullPaths
3389 // by default and there is no negative /FC option that projects
3390 // can use to switch it back. Older toolsets disable this by
3391 // default anyway so this will not hurt them. If the project
3392 // is using an explicit /FC option then parsing flags will
3393 // replace this setting with "true" below.
3394 clOptions.AddFlag("UseFullPaths", "false");
3396 clOptions.AddFlag("AssemblerListingLocation", "$(IntDir)");
3400 // check for managed C++ assembly compiler flag. This overrides any
3401 // /clr* compiler flags which may be defined in the flags variable(s).
3402 if (this->ProjectType != VsProjectType::csproj) {
3403 // Warn if /clr was added manually. This should not be done
3404 // anymore, because cmGeneratorTarget may not be aware that the
3405 // target uses C++/CLI.
3406 if (flags.find("/clr") != std::string::npos ||
3407 flags.find("-clr") != std::string::npos ||
3408 defineFlags.find("/clr") != std::string::npos ||
3409 defineFlags.find("-clr") != std::string::npos) {
3410 if (configName == this->Configurations[0]) {
3411 std::string message =
3412 cmStrCat("For the target \"", this->GeneratorTarget->GetName(),
3413 "\" the /clr compiler flag was added manually. ",
3414 "Set usage of C++/CLI by setting COMMON_LANGUAGE_RUNTIME "
3415 "target property.");
3416 this->Makefile->IssueMessage(MessageType::WARNING, message);
3419 if (cmValue clr =
3420 this->GeneratorTarget->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
3421 std::string clrString = *clr;
3422 if (!clrString.empty()) {
3423 clrString = cmStrCat(':', clrString);
3425 flags += cmStrCat(" /clr", clrString);
3429 // Get includes for this target
3430 if (!this->LangForClCompile.empty()) {
3431 auto includeList = this->GetIncludes(configName, this->LangForClCompile);
3433 auto sysIncludeFlag = this->Makefile->GetDefinition(
3434 cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile));
3436 if (sysIncludeFlag) {
3437 bool gotOneSys = false;
3438 for (auto i : includeList) {
3439 cmSystemTools::ConvertToUnixSlashes(i);
3440 if (this->GeneratorTarget->IsSystemIncludeDirectory(
3441 i, configName, this->LangForClCompile)) {
3442 auto flag = cmTrimWhitespace(*sysIncludeFlag);
3443 if (this->MSTools) {
3444 cmSystemTools::ReplaceString(flag, "-external:I", "/external:I");
3446 clOptions.AppendFlagString("AdditionalOptions",
3447 cmStrCat(flag, " \"", i, '"'));
3448 gotOneSys = true;
3449 } else {
3450 clOptions.AddInclude(i);
3454 if (gotOneSys) {
3455 if (auto sysIncludeFlagWarning = this->Makefile->GetDefinition(
3456 cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile,
3457 "_WARNING"))) {
3458 flags = cmStrCat(flags, ' ', *sysIncludeFlagWarning);
3461 } else {
3462 clOptions.AddIncludes(includeList);
3466 clOptions.Parse(flags);
3467 clOptions.Parse(defineFlags);
3468 std::vector<std::string> targetDefines;
3469 switch (this->ProjectType) {
3470 case VsProjectType::vcxproj:
3471 if (!langForClCompile.empty()) {
3472 this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3473 langForClCompile);
3475 break;
3476 case VsProjectType::csproj:
3477 this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3478 "CSharp");
3479 cm::erase_if(targetDefines, [](std::string const& def) {
3480 return def.find('=') != std::string::npos;
3482 break;
3483 default:
3484 break;
3486 clOptions.AddDefines(targetDefines);
3488 if (this->ProjectType == VsProjectType::csproj) {
3489 clOptions.AppendFlag("DefineConstants", targetDefines);
3492 if (this->MSTools) {
3493 clOptions.SetVerboseMakefile(
3494 this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
3497 // Add C-specific flags expressible in a ClCompile meant for C++.
3498 if (langForClCompile == "CXX"_s) {
3499 std::set<std::string> languages;
3500 this->GeneratorTarget->GetLanguages(languages, configName);
3501 if (languages.count("C")) {
3502 std::string flagsC;
3503 this->LocalGenerator->AddLanguageFlags(
3504 flagsC, this->GeneratorTarget, cmBuildStep::Compile, "C", configName);
3505 this->LocalGenerator->AddCompileOptions(flagsC, this->GeneratorTarget,
3506 "C", configName);
3507 Options optC(this->LocalGenerator, Options::Compiler,
3508 gg->GetClFlagTable());
3509 optC.Parse(flagsC);
3510 if (const char* stdC = optC.GetFlag("LanguageStandard_C")) {
3511 clOptions.AddFlag("LanguageStandard_C", stdC);
3516 // Add a definition for the configuration name.
3517 std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
3518 clOptions.AddDefine(configDefine);
3519 if (const std::string* exportMacro =
3520 this->GeneratorTarget->GetExportMacro()) {
3521 clOptions.AddDefine(*exportMacro);
3524 if (this->MSTools) {
3525 // If we have the VS_WINRT_COMPONENT set then force Compile as WinRT
3526 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
3527 clOptions.AddFlag("CompileAsWinRT", "true");
3528 // For WinRT components, add the _WINRT_DLL define to produce a lib
3529 if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
3530 this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
3531 clOptions.AddDefine("_WINRT_DLL");
3533 } else if (this->GlobalGenerator->TargetsWindowsStore() ||
3534 this->GlobalGenerator->TargetsWindowsPhone() ||
3535 this->Makefile->IsOn("CMAKE_VS_WINRT_BY_DEFAULT")) {
3536 if (!clOptions.IsWinRt()) {
3537 clOptions.AddFlag("CompileAsWinRT", "false");
3540 if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) {
3541 if (cmIsOn(winRT)) {
3542 this->TargetCompileAsWinRT = true;
3547 if (this->ProjectType != VsProjectType::csproj &&
3548 (clOptions.IsManaged() || clOptions.HasFlag("CLRSupport"))) {
3549 this->Managed = true;
3550 std::string managedType = clOptions.HasFlag("CompileAsManaged")
3551 ? clOptions.GetFlag("CompileAsManaged")
3552 : "Mixed";
3553 if (managedType == "Safe"_s || managedType == "Pure"_s) {
3554 // force empty calling convention if safe clr is used
3555 clOptions.AddFlag("CallingConvention", "");
3557 // The default values of these flags are incompatible to
3558 // managed assemblies. We have to force valid values if
3559 // the target is a managed C++ target.
3560 clOptions.AddFlag("ExceptionHandling", "Async");
3561 clOptions.AddFlag("BasicRuntimeChecks", "Default");
3563 if (this->ProjectType == VsProjectType::csproj) {
3564 // /nowin32manifest overrides /win32manifest: parameter
3565 if (clOptions.HasFlag("NoWin32Manifest")) {
3566 clOptions.RemoveFlag("ApplicationManifest");
3570 if (const char* s = clOptions.GetFlag("SpectreMitigation")) {
3571 this->SpectreMitigation[configName] = s;
3572 clOptions.RemoveFlag("SpectreMitigation");
3575 // Remove any target-wide -TC or -TP flag added by the project.
3576 // Such flags are unnecessary and break our model of language selection.
3577 if (langForClCompile == "C"_s || langForClCompile == "CXX"_s) {
3578 clOptions.RemoveFlag("CompileAs");
3581 if (this->ProjectType == VsProjectType::vcxproj && this->MSTools) {
3582 // Suppress Microsoft.Cl.Common.props default settings for which the
3583 // project specifies no flags. Do not let UseDebugLibraries affect them.
3584 if (!clOptions.HasFlag("BasicRuntimeChecks")) {
3585 clOptions.AddFlag("BasicRuntimeChecks", "Default");
3587 if (!clOptions.HasFlag("MinimalRebuild")) {
3588 clOptions.AddFlag("MinimalRebuild", "");
3590 if (!clOptions.HasFlag("Optimization")) {
3591 clOptions.AddFlag("Optimization", "");
3593 if (!clOptions.HasFlag("RuntimeLibrary")) {
3594 clOptions.AddFlag("RuntimeLibrary", "");
3596 if (!clOptions.HasFlag("SupportJustMyCode")) {
3597 clOptions.AddFlag("SupportJustMyCode", "");
3601 this->ClOptions[configName] = std::move(pOptions);
3602 return true;
3605 void cmVisualStudio10TargetGenerator::WriteClOptions(
3606 Elem& e1, std::string const& configName)
3608 Options& clOptions = *(this->ClOptions[configName]);
3609 if (this->ProjectType == VsProjectType::csproj) {
3610 return;
3612 Elem e2(e1, "ClCompile");
3613 OptionsHelper oh(clOptions, e2);
3614 oh.PrependInheritedString("AdditionalOptions");
3615 oh.OutputAdditionalIncludeDirectories(this->LangForClCompile);
3616 oh.OutputFlagMap();
3617 oh.OutputPreprocessorDefinitions(this->LangForClCompile);
3619 if (this->NsightTegra) {
3620 if (cmValue processMax =
3621 this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) {
3622 e2.Element("ProcessMax", *processMax);
3626 if (this->Android) {
3627 e2.Element("ObjectFileName", "$(IntDir)%(filename).o");
3628 } else if (this->MSTools) {
3629 cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
3630 const char* toolset = this->GlobalGenerator->GetPlatformToolset();
3631 cmValue noCompileBatching =
3632 this->GeneratorTarget->GetProperty("VS_NO_COMPILE_BATCHING");
3633 if (noCompileBatching.IsOn() || (toolset && clangToolset.find(toolset))) {
3634 e2.Element("ObjectFileName", "$(IntDir)%(filename).obj");
3635 } else {
3636 e2.Element("ObjectFileName", "$(IntDir)");
3639 // If not in debug mode, write the DebugInformationFormat field
3640 // without value so PDBs don't get generated uselessly. Each tag
3641 // goes on its own line because Visual Studio corrects it this
3642 // way when saving the project after CMake generates it.
3643 if (!clOptions.UsingDebugInfo()) {
3644 Elem e3(e2, "DebugInformationFormat");
3645 e3.SetHasElements();
3648 // Specify the compiler program database file if configured.
3649 std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
3650 if (!pdb.empty()) {
3651 if (this->GlobalGenerator->IsCudaEnabled()) {
3652 // CUDA does not quote paths with spaces correctly when forwarding
3653 // this to the host compiler. Use a relative path to avoid spaces.
3654 // FIXME: We can likely do this even when CUDA is not involved,
3655 // but for now we will make a minimal change.
3656 pdb = this->ConvertPath(pdb, true);
3658 ConvertToWindowsSlash(pdb);
3659 e2.Element("ProgramDataBaseFileName", pdb);
3662 // add AdditionalUsingDirectories
3663 if (this->AdditionalUsingDirectories.count(configName) > 0) {
3664 std::string dirs;
3665 for (auto const& u : this->AdditionalUsingDirectories[configName]) {
3666 if (!dirs.empty()) {
3667 dirs.append(";");
3669 dirs.append(u);
3671 e2.Element("AdditionalUsingDirectories", dirs);
3675 e2.Element("ScanSourceForModuleDependencies",
3676 this->ScanSourceForModuleDependencies[configName] ? "true"
3677 : "false");
3680 bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
3682 return std::all_of(
3683 this->Configurations.begin(), this->Configurations.end(),
3684 [this](std::string const& c) { return this->ComputeRcOptions(c); });
3687 bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
3688 std::string const& configName)
3690 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3691 auto pOptions = cm::make_unique<Options>(
3692 this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
3693 Options& rcOptions = *pOptions;
3695 std::string CONFIG = cmSystemTools::UpperCase(configName);
3696 std::string rcConfigFlagsVar = cmStrCat("CMAKE_RC_FLAGS_", CONFIG);
3697 std::string flags =
3698 cmStrCat(this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS"), ' ',
3699 this->Makefile->GetSafeDefinition(rcConfigFlagsVar));
3701 rcOptions.Parse(flags);
3703 // For historical reasons, add the C preprocessor defines to RC.
3704 Options& clOptions = *(this->ClOptions[configName]);
3705 rcOptions.AddDefines(clOptions.GetDefines());
3707 // Get includes for this target
3708 rcOptions.AddIncludes(this->GetIncludes(configName, "RC"));
3710 this->RcOptions[configName] = std::move(pOptions);
3711 return true;
3714 void cmVisualStudio10TargetGenerator::WriteRCOptions(
3715 Elem& e1, std::string const& configName)
3717 if (!this->MSTools) {
3718 return;
3720 Elem e2(e1, "ResourceCompile");
3722 OptionsHelper rcOptions(*(this->RcOptions[configName]), e2);
3723 rcOptions.OutputPreprocessorDefinitions("RC");
3724 rcOptions.OutputAdditionalIncludeDirectories("RC");
3725 rcOptions.PrependInheritedString("AdditionalOptions");
3726 rcOptions.OutputFlagMap();
3729 bool cmVisualStudio10TargetGenerator::ComputeCudaOptions()
3731 if (!this->GlobalGenerator->IsCudaEnabled()) {
3732 return true;
3734 return std::all_of(this->Configurations.begin(), this->Configurations.end(),
3735 [this](std::string const& c) {
3736 return !this->GeneratorTarget->IsLanguageUsed("CUDA",
3737 c) ||
3738 this->ComputeCudaOptions(c);
3742 bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
3743 std::string const& configName)
3745 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3746 auto pOptions = cm::make_unique<Options>(
3747 this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
3748 Options& cudaOptions = *pOptions;
3750 auto cudaVersion = this->GlobalGenerator->GetPlatformToolsetCudaString();
3752 // Get compile flags for CUDA in this directory.
3753 std::string flags;
3754 this->LocalGenerator->AddLanguageFlags(
3755 flags, this->GeneratorTarget, cmBuildStep::Compile, "CUDA", configName);
3756 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, "CUDA",
3757 configName);
3759 // Get preprocessor definitions for this directory.
3760 std::string defineFlags = this->Makefile->GetDefineFlags();
3762 cudaOptions.Parse(flags);
3763 cudaOptions.Parse(defineFlags);
3764 cudaOptions.ParseFinish();
3766 // If we haven't explicitly enabled GPU debug information
3767 // explicitly disable it
3768 if (!cudaOptions.HasFlag("GPUDebugInfo")) {
3769 cudaOptions.AddFlag("GPUDebugInfo", "false");
3772 // The extension on object libraries the CUDA gives isn't
3773 // consistent with how MSVC generates object libraries for C+, so set
3774 // the default to not have any extension
3775 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).obj");
3777 if (this->GeneratorTarget->GetPropertyAsBool("CUDA_SEPARABLE_COMPILATION")) {
3778 cudaOptions.AddFlag("GenerateRelocatableDeviceCode", "true");
3780 bool notPtxLike = true;
3781 if (this->GeneratorTarget->GetPropertyAsBool("CUDA_PTX_COMPILATION")) {
3782 cudaOptions.AddFlag("NvccCompilation", "ptx");
3783 // We drop the %(Extension) component as CMake expects all PTX files
3784 // to not have the source file extension at all
3785 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
3786 notPtxLike = false;
3788 if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
3789 cudaVersion, "9.0") &&
3790 cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, cudaVersion,
3791 "11.5")) {
3792 // The DriverApi flag before 11.5 ( verified back to 9.0 ) which controls
3793 // PTX compilation doesn't propagate user defines causing
3794 // target_compile_definitions to behave differently for VS +
3795 // PTX compared to other generators so we patch the rules
3796 // to normalize behavior
3797 cudaOptions.AddFlag("DriverApiCommandLineTemplate",
3798 "%(BaseCommandLineTemplate) [CompileOut] [FastMath] "
3799 "[Defines] \"%(FullPath)\"");
3801 } else if (this->GeneratorTarget->GetPropertyAsBool(
3802 "CUDA_CUBIN_COMPILATION")) {
3803 cudaOptions.AddFlag("NvccCompilation", "cubin");
3804 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).cubin");
3805 notPtxLike = false;
3806 } else if (this->GeneratorTarget->GetPropertyAsBool(
3807 "CUDA_FATBIN_COMPILATION")) {
3808 cudaOptions.AddFlag("NvccCompilation", "fatbin");
3809 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).fatbin");
3810 notPtxLike = false;
3811 } else if (this->GeneratorTarget->GetPropertyAsBool(
3812 "CUDA_OPTIX_COMPILATION")) {
3813 cudaOptions.AddFlag("NvccCompilation", "optix-ir");
3814 cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).optixir");
3815 notPtxLike = false;
3818 if (notPtxLike &&
3819 cmSystemTools::VersionCompareGreaterEq(
3820 "8.0", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
3821 // Explicitly state that we want this file to be treated as a
3822 // CUDA file no matter what the file extensions is
3823 // This is only needed for < CUDA 9
3824 cudaOptions.AppendFlagString("AdditionalOptions", "-x cu");
3827 // Specify the compiler program database file if configured.
3828 std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
3829 if (!pdb.empty()) {
3830 // CUDA does not make the directory if it is non-standard.
3831 std::string const pdbDir = cmSystemTools::GetFilenamePath(pdb);
3832 cmSystemTools::MakeDirectory(pdbDir);
3833 if (cmSystemTools::VersionCompareGreaterEq(
3834 "9.2", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
3835 // CUDA does not have a field for this and does not honor the
3836 // ProgramDataBaseFileName field in ClCompile. Work around this
3837 // limitation by creating the directory and passing the flag ourselves.
3838 pdb = this->ConvertPath(pdb, true);
3839 ConvertToWindowsSlash(pdb);
3840 std::string const clFd = cmStrCat(R"(-Xcompiler="-Fd\")", pdb, R"(\"")");
3841 cudaOptions.AppendFlagString("AdditionalOptions", clFd);
3845 // CUDA automatically passes the proper '--machine' flag to nvcc
3846 // for the current architecture, but does not reflect this default
3847 // in the user-visible IDE settings. Set it explicitly.
3848 if (this->Platform == "x64"_s) {
3849 cudaOptions.AddFlag("TargetMachinePlatform", "64");
3852 // Convert the host compiler options to the toolset's abstractions
3853 // using a secondary flag table.
3854 cudaOptions.ClearTables();
3855 cudaOptions.AddTable(gg->GetCudaHostFlagTable());
3856 cudaOptions.Reparse("AdditionalCompilerOptions");
3858 // `CUDA 8.0.targets` places AdditionalCompilerOptions before nvcc!
3859 // Pass them through -Xcompiler in AdditionalOptions instead.
3860 if (const char* acoPtr = cudaOptions.GetFlag("AdditionalCompilerOptions")) {
3861 std::string aco = acoPtr;
3862 cudaOptions.RemoveFlag("AdditionalCompilerOptions");
3863 if (!aco.empty()) {
3864 aco = this->LocalGenerator->EscapeForShell(aco, false);
3865 cudaOptions.AppendFlagString("AdditionalOptions",
3866 cmStrCat("-Xcompiler=", aco));
3870 cudaOptions.FixCudaCodeGeneration();
3872 std::vector<std::string> targetDefines;
3873 this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3874 "CUDA");
3875 cudaOptions.AddDefines(targetDefines);
3877 // Add a definition for the configuration name.
3878 std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
3879 cudaOptions.AddDefine(configDefine);
3880 if (const std::string* exportMacro =
3881 this->GeneratorTarget->GetExportMacro()) {
3882 cudaOptions.AddDefine(*exportMacro);
3885 // Get includes for this target
3886 cudaOptions.AddIncludes(this->GetIncludes(configName, "CUDA"));
3887 cudaOptions.AddFlag("UseHostInclude", "false");
3889 // Add runtime library selection flag.
3890 std::string const& cudaRuntime =
3891 this->GeneratorTarget->GetRuntimeLinkLibrary("CUDA", configName);
3892 if (cudaRuntime == "STATIC"_s) {
3893 cudaOptions.AddFlag("CudaRuntime", "Static");
3894 } else if (cudaRuntime == "SHARED"_s) {
3895 cudaOptions.AddFlag("CudaRuntime", "Shared");
3896 } else if (cudaRuntime == "NONE"_s) {
3897 cudaOptions.AddFlag("CudaRuntime", "None");
3900 if (this->ProjectType == VsProjectType::vcxproj && this->MSTools) {
3901 // Suppress inheritance of host compiler optimization flags
3902 // when the project does not specify any optimization flags for CUDA.
3903 if (!cudaOptions.HasFlag("Optimization")) {
3904 cudaOptions.AddFlag("Optimization", "");
3908 this->CudaOptions[configName] = std::move(pOptions);
3909 return true;
3912 void cmVisualStudio10TargetGenerator::WriteCudaOptions(
3913 Elem& e1, std::string const& configName)
3915 if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled() ||
3916 !this->GeneratorTarget->IsLanguageUsed("CUDA", configName)) {
3917 return;
3919 Elem e2(e1, "CudaCompile");
3921 OptionsHelper cudaOptions(*(this->CudaOptions[configName]), e2);
3922 cudaOptions.OutputAdditionalIncludeDirectories("CUDA");
3923 cudaOptions.OutputPreprocessorDefinitions("CUDA");
3924 cudaOptions.PrependInheritedString("AdditionalOptions");
3925 cudaOptions.OutputFlagMap();
3928 bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
3930 if (!this->GlobalGenerator->IsCudaEnabled()) {
3931 return true;
3933 return std::all_of(
3934 this->Configurations.begin(), this->Configurations.end(),
3935 [this](std::string const& c) { return this->ComputeCudaLinkOptions(c); });
3938 bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
3939 std::string const& configName)
3941 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3942 auto pOptions = cm::make_unique<Options>(
3943 this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
3944 Options& cudaLinkOptions = *pOptions;
3946 cmGeneratorTarget::DeviceLinkSetter setter(*this->GeneratorTarget);
3948 // Determine if we need to do a device link
3949 const bool doDeviceLinking = requireDeviceLinking(
3950 *this->GeneratorTarget, *this->LocalGenerator, configName);
3952 cudaLinkOptions.AddFlag("PerformDeviceLink",
3953 doDeviceLinking ? "true" : "false");
3955 // Add extra flags for device linking
3956 cudaLinkOptions.AppendFlagString(
3957 "AdditionalOptions",
3958 this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_FLAGS"));
3959 cudaLinkOptions.AppendFlagString(
3960 "AdditionalOptions",
3961 this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS"));
3963 std::vector<std::string> linkOpts;
3964 std::string linkFlags;
3965 this->GeneratorTarget->GetLinkOptions(linkOpts, configName, "CUDA");
3966 // LINK_OPTIONS are escaped.
3967 this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
3969 cmComputeLinkInformation* pcli =
3970 this->GeneratorTarget->GetLinkInformation(configName);
3971 if (doDeviceLinking && pcli) {
3973 cmLinkLineDeviceComputer computer(
3974 this->LocalGenerator,
3975 this->LocalGenerator->GetStateSnapshot().GetDirectory());
3976 std::string ignored_;
3977 this->LocalGenerator->GetDeviceLinkFlags(computer, configName, ignored_,
3978 linkFlags, ignored_, ignored_,
3979 this->GeneratorTarget);
3981 this->LocalGenerator->AddLanguageFlagsForLinking(
3982 linkFlags, this->GeneratorTarget, "CUDA", configName);
3984 cudaLinkOptions.AppendFlagString("AdditionalOptions", linkFlags);
3986 if (doDeviceLinking) {
3987 std::vector<std::string> libVec;
3988 auto const& kinded = this->GeneratorTarget->GetKindedSources(configName);
3989 // CMake conversion uses full paths when possible to allow deeper trees.
3990 // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
3991 // we must use relative paths.
3992 const bool forceRelative = true;
3993 for (cmGeneratorTarget::SourceAndKind const& si : kinded.Sources) {
3994 switch (si.Kind) {
3995 case cmGeneratorTarget::SourceKindExternalObject: {
3996 std::string path =
3997 this->ConvertPath(si.Source.Value->GetFullPath(), forceRelative);
3998 ConvertToWindowsSlash(path);
3999 libVec.emplace_back(std::move(path));
4000 } break;
4001 default:
4002 break;
4005 // For static libraries that have device linking enabled compute
4006 // the libraries
4007 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
4008 cmComputeLinkInformation& cli = *pcli;
4009 cmLinkLineDeviceComputer computer(
4010 this->LocalGenerator,
4011 this->LocalGenerator->GetStateSnapshot().GetDirectory());
4012 std::vector<BT<std::string>> btLibVec;
4013 computer.ComputeLinkLibraries(cli, std::string{}, btLibVec);
4014 for (auto const& item : btLibVec) {
4015 libVec.emplace_back(item.Value);
4018 if (!libVec.empty()) {
4019 cudaLinkOptions.AddFlag("AdditionalDependencies", libVec);
4023 this->CudaLinkOptions[configName] = std::move(pOptions);
4024 return true;
4027 void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
4028 Elem& e1, std::string const& configName)
4030 // We need to write link options for OBJECT libraries so that
4031 // we override the default device link behavior ( enabled ) when
4032 // building object libraries with ptx/optix-ir/etc
4033 if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
4034 return;
4037 if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
4038 return;
4041 Elem e2(e1, "CudaLink");
4042 OptionsHelper cudaLinkOptions(*(this->CudaLinkOptions[configName]), e2);
4043 cudaLinkOptions.OutputFlagMap();
4046 bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions()
4048 if (!this->GlobalGenerator->IsMarmasmEnabled()) {
4049 return true;
4051 return std::all_of(
4052 this->Configurations.begin(), this->Configurations.end(),
4053 [this](std::string const& c) { return this->ComputeMarmasmOptions(c); });
4056 bool cmVisualStudio10TargetGenerator::ComputeMarmasmOptions(
4057 std::string const& configName)
4059 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4060 auto pOptions = cm::make_unique<Options>(
4061 this->LocalGenerator, Options::MarmasmCompiler, gg->GetMarmasmFlagTable());
4062 Options& marmasmOptions = *pOptions;
4064 std::string flags;
4065 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
4066 cmBuildStep::Compile, "ASM_MARMASM",
4067 configName);
4068 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
4069 "ASM_MARMASM", configName);
4071 marmasmOptions.Parse(flags);
4073 // Get includes for this target
4074 marmasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MARMASM"));
4076 this->MarmasmOptions[configName] = std::move(pOptions);
4077 return true;
4080 void cmVisualStudio10TargetGenerator::WriteMarmasmOptions(
4081 Elem& e1, std::string const& configName)
4083 if (!this->MSTools || !this->GlobalGenerator->IsMarmasmEnabled()) {
4084 return;
4086 Elem e2(e1, "MARMASM");
4088 // Preprocessor definitions and includes are shared with clOptions.
4089 OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
4090 clOptions.OutputPreprocessorDefinitions("ASM_MARMASM");
4092 OptionsHelper marmasmOptions(*(this->MarmasmOptions[configName]), e2);
4093 marmasmOptions.OutputAdditionalIncludeDirectories("ASM_MARMASM");
4094 marmasmOptions.PrependInheritedString("AdditionalOptions");
4095 marmasmOptions.OutputFlagMap();
4098 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
4100 if (!this->GlobalGenerator->IsMasmEnabled()) {
4101 return true;
4103 return std::all_of(
4104 this->Configurations.begin(), this->Configurations.end(),
4105 [this](std::string const& c) { return this->ComputeMasmOptions(c); });
4108 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
4109 std::string const& configName)
4111 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4112 auto pOptions = cm::make_unique<Options>(
4113 this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
4114 Options& masmOptions = *pOptions;
4116 // MSBuild enables debug information by default.
4117 // Disable it explicitly unless a flag parsed below re-enables it.
4118 masmOptions.AddFlag("GenerateDebugInformation", "false");
4120 std::string flags;
4121 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
4122 cmBuildStep::Compile, "ASM_MASM",
4123 configName);
4124 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
4125 "ASM_MASM", configName);
4127 masmOptions.Parse(flags);
4129 // Get includes for this target
4130 masmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MASM"));
4132 this->MasmOptions[configName] = std::move(pOptions);
4133 return true;
4136 void cmVisualStudio10TargetGenerator::WriteMasmOptions(
4137 Elem& e1, std::string const& configName)
4139 if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
4140 return;
4142 Elem e2(e1, "MASM");
4144 // Preprocessor definitions and includes are shared with clOptions.
4145 OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
4146 clOptions.OutputPreprocessorDefinitions("ASM_MASM");
4148 OptionsHelper masmOptions(*(this->MasmOptions[configName]), e2);
4149 masmOptions.OutputAdditionalIncludeDirectories("ASM_MASM");
4150 masmOptions.PrependInheritedString("AdditionalOptions");
4151 masmOptions.OutputFlagMap();
4154 bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
4156 if (!this->GlobalGenerator->IsNasmEnabled()) {
4157 return true;
4159 return std::all_of(
4160 this->Configurations.begin(), this->Configurations.end(),
4161 [this](std::string const& c) { return this->ComputeNasmOptions(c); });
4164 bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
4165 std::string const& configName)
4167 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4168 auto pOptions = cm::make_unique<Options>(
4169 this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
4170 Options& nasmOptions = *pOptions;
4172 std::string flags;
4173 this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
4174 cmBuildStep::Compile, "ASM_NASM",
4175 configName);
4176 this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
4177 "ASM_NASM", configName);
4178 flags += " -f";
4179 flags += this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_OBJECT_FORMAT");
4180 nasmOptions.Parse(flags);
4182 // Get includes for this target
4183 nasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_NASM"));
4185 this->NasmOptions[configName] = std::move(pOptions);
4186 return true;
4189 void cmVisualStudio10TargetGenerator::WriteNasmOptions(
4190 Elem& e1, std::string const& configName)
4192 if (!this->GlobalGenerator->IsNasmEnabled()) {
4193 return;
4195 Elem e2(e1, "NASM");
4197 OptionsHelper nasmOptions(*(this->NasmOptions[configName]), e2);
4198 nasmOptions.OutputAdditionalIncludeDirectories("ASM_NASM");
4199 nasmOptions.OutputFlagMap();
4200 nasmOptions.PrependInheritedString("AdditionalOptions");
4201 nasmOptions.OutputPreprocessorDefinitions("ASM_NASM");
4203 // Preprocessor definitions and includes are shared with clOptions.
4204 OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
4205 clOptions.OutputPreprocessorDefinitions("ASM_NASM");
4208 void cmVisualStudio10TargetGenerator::WriteLibOptions(
4209 Elem& e1, std::string const& config)
4211 if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
4212 this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
4213 return;
4216 const std::string& linkLanguage =
4217 this->GeneratorTarget->GetLinkClosure(config)->LinkerLanguage;
4219 std::string libflags;
4220 this->LocalGenerator->GetStaticLibraryFlags(libflags, config, linkLanguage,
4221 this->GeneratorTarget);
4222 if (!libflags.empty()) {
4223 Elem e2(e1, "Lib");
4224 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4225 cmVS10GeneratorOptions libOptions(this->LocalGenerator,
4226 cmVisualStudioGeneratorOptions::Linker,
4227 gg->GetLibFlagTable(), this);
4228 libOptions.Parse(libflags);
4229 OptionsHelper oh(libOptions, e2);
4230 oh.PrependInheritedString("AdditionalOptions");
4231 oh.OutputFlagMap();
4234 // We cannot generate metadata for static libraries. WindowsPhone
4235 // and WindowsStore tools look at GenerateWindowsMetadata in the
4236 // Link tool options even for static libraries.
4237 if (this->GlobalGenerator->TargetsWindowsPhone() ||
4238 this->GlobalGenerator->TargetsWindowsStore()) {
4239 Elem e2(e1, "Link");
4240 e2.Element("GenerateWindowsMetadata", "false");
4244 void cmVisualStudio10TargetGenerator::WriteManifestOptions(
4245 Elem& e1, std::string const& config)
4247 if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
4248 this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
4249 this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
4250 return;
4253 std::vector<cmSourceFile const*> manifest_srcs;
4254 this->GeneratorTarget->GetManifests(manifest_srcs, config);
4256 cmValue dpiAware = this->GeneratorTarget->GetProperty("VS_DPI_AWARE");
4258 if (!manifest_srcs.empty() || dpiAware) {
4259 Elem e2(e1, "Manifest");
4260 if (!manifest_srcs.empty()) {
4261 std::ostringstream oss;
4262 for (cmSourceFile const* mi : manifest_srcs) {
4263 std::string m = this->ConvertPath(mi->GetFullPath(), false);
4264 ConvertToWindowsSlash(m);
4265 oss << m << ";";
4267 e2.Element("AdditionalManifestFiles", oss.str());
4269 if (dpiAware) {
4270 if (*dpiAware == "PerMonitor"_s) {
4271 e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware");
4272 } else if (dpiAware.IsOn()) {
4273 e2.Element("EnableDpiAwareness", "true");
4274 } else if (dpiAware.IsOff()) {
4275 e2.Element("EnableDpiAwareness", "false");
4276 } else {
4277 cmSystemTools::Error(
4278 cmStrCat("Bad parameter for VS_DPI_AWARE: ", *dpiAware));
4284 void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
4285 Elem& e1, std::string const& configName)
4287 // Look through the sources for AndroidManifest.xml and use
4288 // its location as the root source directory.
4289 std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
4291 for (cmGeneratorTarget::AllConfigSource const& source :
4292 this->GeneratorTarget->GetAllConfigSources()) {
4293 if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
4294 "androidmanifest.xml" ==
4295 cmSystemTools::LowerCase(source.Source->GetLocation().GetName())) {
4296 rootDir = source.Source->GetLocation().GetDirectory();
4297 break;
4302 // Tell MSBuild to launch Ant.
4303 Elem e2(e1, "AntBuild");
4305 std::string antBuildPath = rootDir;
4306 ConvertToWindowsSlash(antBuildPath);
4307 e2.Element("AntBuildPath", antBuildPath);
4310 if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
4311 e2.Element("SkipAntStep", "true");
4314 if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
4315 e2.Element("EnableProGuard", "true");
4318 if (cmValue proGuardConfigLocation =
4319 this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
4320 e2.Element("ProGuardConfigLocation", *proGuardConfigLocation);
4323 if (cmValue securePropertiesLocation =
4324 this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
4325 e2.Element("SecurePropertiesLocation", *securePropertiesLocation);
4328 if (cmValue nativeLibDirectoriesExpression =
4329 this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
4330 std::string nativeLibDirs = cmGeneratorExpression::Evaluate(
4331 *nativeLibDirectoriesExpression, this->LocalGenerator, configName);
4332 e2.Element("NativeLibDirectories", nativeLibDirs);
4335 if (cmValue nativeLibDependenciesExpression =
4336 this->GeneratorTarget->GetProperty(
4337 "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
4338 std::string nativeLibDeps = cmGeneratorExpression::Evaluate(
4339 *nativeLibDependenciesExpression, this->LocalGenerator, configName);
4340 e2.Element("NativeLibDependencies", nativeLibDeps);
4343 if (cmValue javaSourceDir =
4344 this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
4345 e2.Element("JavaSourceDir", *javaSourceDir);
4348 if (cmValue jarDirectoriesExpression =
4349 this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
4350 std::string jarDirectories = cmGeneratorExpression::Evaluate(
4351 *jarDirectoriesExpression, this->LocalGenerator, configName);
4352 e2.Element("JarDirectories", jarDirectories);
4355 if (cmValue jarDeps =
4356 this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
4357 e2.Element("JarDependencies", *jarDeps);
4360 if (cmValue assetsDirectories =
4361 this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
4362 e2.Element("AssetsDirectories", *assetsDirectories);
4366 std::string manifest_xml = cmStrCat(rootDir, "/AndroidManifest.xml");
4367 ConvertToWindowsSlash(manifest_xml);
4368 e2.Element("AndroidManifestLocation", manifest_xml);
4371 if (cmValue antAdditionalOptions =
4372 this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
4373 e2.Element("AdditionalOptions",
4374 cmStrCat(*antAdditionalOptions, " %(AdditionalOptions)"));
4378 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
4380 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
4381 this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
4382 this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
4383 for (std::string const& c : this->Configurations) {
4384 if (!this->ComputeLinkOptions(c)) {
4385 return false;
4389 return true;
4392 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
4393 std::string const& config)
4395 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4396 auto pOptions = cm::make_unique<Options>(
4397 this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this);
4398 Options& linkOptions = *pOptions;
4400 cmGeneratorTarget::LinkClosure const* linkClosure =
4401 this->GeneratorTarget->GetLinkClosure(config);
4403 const std::string& linkLanguage = linkClosure->LinkerLanguage;
4404 if (linkLanguage.empty()) {
4405 cmSystemTools::Error(cmStrCat(
4406 "CMake can not determine linker language for target: ", this->Name));
4407 return false;
4410 std::string CONFIG = cmSystemTools::UpperCase(config);
4412 const char* linkType = "SHARED";
4413 if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
4414 linkType = "MODULE";
4416 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4417 linkType = "EXE";
4419 std::string flags;
4420 std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS");
4421 flags += ' ';
4422 flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase);
4423 std::string linkFlagVar = cmStrCat(linkFlagVarBase, '_', CONFIG);
4424 flags += ' ';
4425 flags += this->Makefile->GetRequiredDefinition(linkFlagVar);
4426 cmValue targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS");
4427 if (targetLinkFlags) {
4428 flags += ' ';
4429 flags += *targetLinkFlags;
4431 std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG);
4432 if (cmValue flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) {
4433 flags += ' ';
4434 flags += *flagsConfig;
4437 std::vector<std::string> opts;
4438 this->GeneratorTarget->GetLinkOptions(opts, config, linkLanguage);
4439 // LINK_OPTIONS are escaped.
4440 this->LocalGenerator->AppendCompileOptions(flags, opts);
4442 cmComputeLinkInformation* pcli =
4443 this->GeneratorTarget->GetLinkInformation(config);
4444 if (!pcli) {
4445 cmSystemTools::Error(
4446 cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
4447 this->Name));
4448 return false;
4450 cmComputeLinkInformation& cli = *pcli;
4452 std::vector<std::string> libVec;
4453 std::vector<std::string> vsTargetVec;
4454 this->AddLibraries(cli, libVec, vsTargetVec, config);
4455 std::string standardLibsVar =
4456 cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
4457 std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar);
4458 cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
4459 linkOptions.AddFlag("AdditionalDependencies", libVec);
4461 // Populate TargetsFileAndConfigsVec
4462 for (std::string const& ti : vsTargetVec) {
4463 this->AddTargetsFileAndConfigPair(ti, config);
4466 std::vector<std::string> linkDirs;
4467 std::vector<std::string> const& ldirs = cli.GetDirectories();
4468 for (std::string const& d : ldirs) {
4469 // first just full path
4470 linkDirs.push_back(d);
4471 // next path with configuration type Debug, Release, etc
4472 linkDirs.emplace_back(cmStrCat(d, "/$(Configuration)"));
4475 std::string const& linkDirsString = this->Makefile->GetSafeDefinition(
4476 cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LINK_DIRECTORIES"));
4477 for (const std::string& d : cmList(linkDirsString)) {
4478 linkDirs.push_back(d);
4481 linkDirs.push_back("%(AdditionalLibraryDirectories)");
4482 linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
4484 cmGeneratorTarget::Names targetNames;
4485 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4486 targetNames = this->GeneratorTarget->GetExecutableNames(config);
4487 } else {
4488 targetNames = this->GeneratorTarget->GetLibraryNames(config);
4491 if (this->MSTools) {
4492 if (this->GeneratorTarget->IsWin32Executable(config)) {
4493 if (this->GlobalGenerator->TargetsWindowsCE()) {
4494 linkOptions.AddFlag("SubSystem", "WindowsCE");
4495 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4496 if (this->ClOptions[config]->UsingUnicode()) {
4497 linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
4498 } else {
4499 linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
4502 } else {
4503 linkOptions.AddFlag("SubSystem", "Windows");
4505 } else {
4506 if (this->GlobalGenerator->TargetsWindowsCE()) {
4507 linkOptions.AddFlag("SubSystem", "WindowsCE");
4508 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4509 if (this->ClOptions[config]->UsingUnicode()) {
4510 linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
4511 } else {
4512 linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
4515 } else {
4516 linkOptions.AddFlag("SubSystem", "Console");
4520 if (cmValue stackVal = this->Makefile->GetDefinition(
4521 cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"))) {
4522 linkOptions.AddFlag("StackReserveSize", *stackVal);
4525 linkOptions.AddFlag("GenerateDebugInformation", "false");
4527 std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config),
4528 '/', targetNames.PDB);
4529 if (!targetNames.ImportLibrary.empty()) {
4530 std::string imLib =
4531 cmStrCat(this->GeneratorTarget->GetDirectory(
4532 config, cmStateEnums::ImportLibraryArtifact),
4533 '/', targetNames.ImportLibrary);
4535 linkOptions.AddFlag("ImportLibrary", imLib);
4537 linkOptions.AddFlag("ProgramDataBaseFile", pdb);
4539 // A Windows Runtime component uses internal .NET metadata,
4540 // so does not have an import library.
4541 if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
4542 this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
4543 linkOptions.AddFlag("GenerateWindowsMetadata", "true");
4544 } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
4545 this->GlobalGenerator->TargetsWindowsStore()) {
4546 // WindowsPhone and WindowsStore components are in an app container
4547 // and produce WindowsMetadata. If we are not producing a WINRT
4548 // component, then do not generate the metadata here.
4549 linkOptions.AddFlag("GenerateWindowsMetadata", "false");
4552 if (this->GlobalGenerator->TargetsWindowsPhone() &&
4553 this->GlobalGenerator->GetSystemVersion() == "8.0"_s) {
4554 // WindowsPhone 8.0 does not have ole32.
4555 linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
4557 } else if (this->NsightTegra) {
4558 linkOptions.AddFlag("SoName", targetNames.SharedObject);
4561 linkOptions.Parse(flags);
4562 linkOptions.FixManifestUACFlags();
4564 if (this->MSTools) {
4565 cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
4566 this->GeneratorTarget->GetModuleDefinitionInfo(config);
4567 if (mdi && !mdi->DefFile.empty()) {
4568 linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile);
4570 linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
4571 "%(IgnoreSpecificDefaultLibraries)");
4574 // VS 2015 without all updates has a v140 toolset whose
4575 // GenerateDebugInformation expects No/Debug instead of false/true.
4576 if (gg->GetPlatformToolsetNeedsDebugEnum()) {
4577 if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
4578 if (strcmp(debug, "false") == 0) {
4579 linkOptions.AddFlag("GenerateDebugInformation", "No");
4580 } else if (strcmp(debug, "true") == 0) {
4581 linkOptions.AddFlag("GenerateDebugInformation", "Debug");
4586 // Managed code cannot be linked with /DEBUG:FASTLINK
4587 if (this->Managed) {
4588 if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
4589 if (strcmp(debug, "DebugFastLink") == 0) {
4590 linkOptions.AddFlag("GenerateDebugInformation", "Debug");
4595 this->LinkOptions[config] = std::move(pOptions);
4596 return true;
4599 bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
4601 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
4602 for (std::string const& c : this->Configurations) {
4603 if (!this->ComputeLibOptions(c)) {
4604 return false;
4608 return true;
4611 bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
4612 std::string const& config)
4614 cmComputeLinkInformation* pcli =
4615 this->GeneratorTarget->GetLinkInformation(config);
4616 if (!pcli) {
4617 cmSystemTools::Error(
4618 cmStrCat("CMake can not compute cmComputeLinkInformation for target: ",
4619 this->Name));
4620 return false;
4623 cmComputeLinkInformation& cli = *pcli;
4624 using ItemVector = cmComputeLinkInformation::ItemVector;
4625 const ItemVector& libs = cli.GetItems();
4626 for (cmComputeLinkInformation::Item const& l : libs) {
4627 if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
4628 cmVS10IsTargetsFile(l.Value.Value)) {
4629 std::string path =
4630 this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
4631 ConvertToWindowsSlash(path);
4632 this->AddTargetsFileAndConfigPair(path, config);
4636 return true;
4639 void cmVisualStudio10TargetGenerator::WriteLinkOptions(
4640 Elem& e1, std::string const& config)
4642 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
4643 this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
4644 return;
4646 if (this->ProjectType == VsProjectType::csproj) {
4647 return;
4651 Elem e2(e1, "Link");
4652 OptionsHelper linkOptions(*(this->LinkOptions[config]), e2);
4653 linkOptions.PrependInheritedString("AdditionalOptions");
4654 linkOptions.OutputFlagMap();
4657 if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
4658 this->GeneratorTarget)) {
4659 Elem e2(e1, "ProjectReference");
4660 e2.Element("LinkLibraryDependencies", "false");
4664 void cmVisualStudio10TargetGenerator::AddLibraries(
4665 const cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
4666 std::vector<std::string>& vsTargetVec, const std::string& config)
4668 using ItemVector = cmComputeLinkInformation::ItemVector;
4669 ItemVector const& libs = cli.GetItems();
4670 for (cmComputeLinkInformation::Item const& l : libs) {
4671 if (l.Target) {
4672 auto managedType = l.Target->GetManagedType(config);
4673 if (managedType != cmGeneratorTarget::ManagedType::Native &&
4674 this->GeneratorTarget->GetManagedType(config) !=
4675 cmGeneratorTarget::ManagedType::Native &&
4676 l.Target->IsImported() &&
4677 l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
4678 auto location = l.Target->GetFullPath(config);
4679 if (!location.empty()) {
4680 ConvertToWindowsSlash(location);
4681 switch (this->ProjectType) {
4682 case VsProjectType::csproj:
4683 // If the target we want to "link" to is an imported managed
4684 // target and this is a C# project, we add a hint reference. This
4685 // reference is written to project file in
4686 // WriteDotNetReferences().
4687 this->DotNetHintReferences[config].push_back(
4688 DotNetHintReference(l.Target->GetName(), location));
4689 break;
4690 case VsProjectType::vcxproj:
4691 // Add path of assembly to list of using-directories, so the
4692 // managed assembly can be used by '#using <assembly.dll>' in
4693 // code.
4694 this->AdditionalUsingDirectories[config].insert(
4695 cmSystemTools::GetFilenamePath(location));
4696 break;
4697 default:
4698 // In .proj files, we wouldn't be referencing libraries.
4699 break;
4703 // Do not allow C# targets to be added to the LIB listing. LIB files are
4704 // used for linking C++ dependencies. C# libraries do not have lib files.
4705 // Instead, they compile down to C# reference libraries (DLL files). The
4706 // `<ProjectReference>` elements added to the vcxproj are enough for the
4707 // IDE to deduce the DLL file required by other C# projects that need its
4708 // reference library.
4709 if (managedType == cmGeneratorTarget::ManagedType::Managed) {
4710 continue;
4714 if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
4715 std::string path =
4716 this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
4717 ConvertToWindowsSlash(path);
4718 if (cmVS10IsTargetsFile(l.Value.Value)) {
4719 vsTargetVec.push_back(path);
4720 } else {
4721 libVec.push_back(l.HasFeature() ? l.GetFormattedItem(path).Value
4722 : path);
4724 } else if (!l.Target ||
4725 (l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
4726 l.Target->GetType() != cmStateEnums::OBJECT_LIBRARY)) {
4727 libVec.push_back(l.Value.Value);
4732 void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
4733 std::string const& targetsFile, std::string const& config)
4735 for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) {
4736 if (cmSystemTools::ComparePath(targetsFile, i.File)) {
4737 if (!cm::contains(i.Configs, config)) {
4738 i.Configs.push_back(config);
4740 return;
4743 TargetsFileAndConfigs entry;
4744 entry.File = targetsFile;
4745 entry.Configs.push_back(config);
4746 this->TargetsFileAndConfigsVec.push_back(entry);
4749 void cmVisualStudio10TargetGenerator::WriteMidlOptions(
4750 Elem& e1, std::string const& configName)
4752 if (!this->MSTools) {
4753 return;
4755 if (this->ProjectType == VsProjectType::csproj) {
4756 return;
4758 if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
4759 return;
4762 // This processes *any* of the .idl files specified in the project's file
4763 // list (and passed as the item metadata %(Filename) expressing the rule
4764 // input filename) into output files at the per-config *build* dir
4765 // ($(IntDir)) each.
4767 // IOW, this MIDL section is intended to provide a fully generic syntax
4768 // content suitable for most cases (read: if you get errors, then it's quite
4769 // probable that the error is on your side of the .idl setup).
4771 // Also, note that the marked-as-generated _i.c file in the Visual Studio
4772 // generator case needs to be referred to as $(IntDir)\foo_i.c at the
4773 // project's file list, otherwise the compiler-side processing won't pick it
4774 // up (for non-directory form, it ends up looking in project binary dir
4775 // only). Perhaps there's something to be done to make this more automatic
4776 // on the CMake side?
4777 std::vector<std::string> const includes =
4778 this->GetIncludes(configName, "MIDL");
4779 std::ostringstream oss;
4780 for (std::string const& i : includes) {
4781 oss << i << ";";
4783 oss << "%(AdditionalIncludeDirectories)";
4785 Elem e2(e1, "Midl");
4786 e2.Element("AdditionalIncludeDirectories", oss.str());
4787 e2.Element("OutputDirectory", "$(ProjectDir)/$(IntDir)");
4788 e2.Element("HeaderFileName", "%(Filename).h");
4789 e2.Element("TypeLibraryName", "%(Filename).tlb");
4790 e2.Element("InterfaceIdentifierFileName", "%(Filename)_i.c");
4791 e2.Element("ProxyFileName", "%(Filename)_p.c");
4794 void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups(Elem& e0)
4796 if (this->ProjectType == VsProjectType::csproj) {
4797 return;
4799 for (const std::string& c : this->Configurations) {
4800 Elem e1(e0, "ItemDefinitionGroup");
4801 e1.Attribute("Condition", this->CalcCondition(c));
4803 // output cl compile flags <ClCompile></ClCompile>
4804 if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
4805 this->WriteClOptions(e1, c);
4806 // output rc compile flags <ResourceCompile></ResourceCompile>
4807 this->WriteRCOptions(e1, c);
4808 this->WriteCudaOptions(e1, c);
4809 this->WriteMarmasmOptions(e1, c);
4810 this->WriteMasmOptions(e1, c);
4811 this->WriteNasmOptions(e1, c);
4813 // output midl flags <Midl></Midl>
4814 this->WriteMidlOptions(e1, c);
4815 // write events
4816 if (this->ProjectType != VsProjectType::csproj) {
4817 this->WriteEvents(e1, c);
4819 // output link flags <Link></Link>
4820 this->WriteLinkOptions(e1, c);
4821 this->WriteCudaLinkOptions(e1, c);
4822 // output lib flags <Lib></Lib>
4823 this->WriteLibOptions(e1, c);
4824 // output manifest flags <Manifest></Manifest>
4825 this->WriteManifestOptions(e1, c);
4826 if (this->NsightTegra &&
4827 this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
4828 this->WriteAntBuildOptions(e1, c);
4833 void cmVisualStudio10TargetGenerator::WriteEvents(
4834 Elem& e1, std::string const& configName)
4836 bool addedPrelink = false;
4837 cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
4838 this->GeneratorTarget->GetModuleDefinitionInfo(configName);
4839 if (mdi && mdi->DefFileGenerated) {
4840 addedPrelink = true;
4841 std::vector<cmCustomCommand> commands =
4842 this->GeneratorTarget->GetPreLinkCommands();
4843 this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
4844 commands, configName);
4845 this->WriteEvent(e1, "PreLinkEvent", commands, configName);
4847 if (!addedPrelink) {
4848 this->WriteEvent(e1, "PreLinkEvent",
4849 this->GeneratorTarget->GetPreLinkCommands(), configName);
4851 this->WriteEvent(e1, "PreBuildEvent",
4852 this->GeneratorTarget->GetPreBuildCommands(), configName);
4853 this->WriteEvent(e1, "PostBuildEvent",
4854 this->GeneratorTarget->GetPostBuildCommands(), configName);
4857 void cmVisualStudio10TargetGenerator::WriteEvent(
4858 Elem& e1, const std::string& name,
4859 std::vector<cmCustomCommand> const& commands, std::string const& configName)
4861 if (commands.empty()) {
4862 return;
4864 cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
4865 std::string script;
4866 const char* pre = "";
4867 std::string comment;
4868 bool stdPipesUTF8 = false;
4869 for (cmCustomCommand const& cc : commands) {
4870 cmCustomCommandGenerator ccg(cc, configName, lg);
4871 if (!ccg.HasOnlyEmptyCommandLines()) {
4872 comment += pre;
4873 comment += lg->ConstructComment(ccg);
4874 script += pre;
4875 pre = "\n";
4876 script += lg->ConstructScript(ccg);
4878 stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
4881 if (!script.empty()) {
4882 script += lg->FinishConstructScript(this->ProjectType);
4884 comment = cmVS10EscapeComment(comment);
4885 if (this->ProjectType != VsProjectType::csproj) {
4886 Elem e2(e1, name);
4887 if (stdPipesUTF8) {
4888 this->WriteStdOutEncodingUtf8(e2);
4890 e2.Element("Message", comment);
4891 e2.Element("Command", script);
4892 } else {
4893 std::string strippedComment = comment;
4894 strippedComment.erase(
4895 std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
4896 strippedComment.end());
4897 std::ostringstream oss;
4898 if (!comment.empty() && !strippedComment.empty()) {
4899 oss << "echo " << comment << "\n";
4901 oss << script << "\n";
4902 e1.Element(name, oss.str());
4906 void cmVisualStudio10TargetGenerator::WriteSdkStyleEvents(
4907 Elem& e0, std::string const& configName)
4909 this->WriteSdkStyleEvent(e0, "PreLink", "BeforeTargets", "Link",
4910 this->GeneratorTarget->GetPreLinkCommands(),
4911 configName);
4912 this->WriteSdkStyleEvent(e0, "PreBuild", "BeforeTargets", "PreBuildEvent",
4913 this->GeneratorTarget->GetPreBuildCommands(),
4914 configName);
4915 this->WriteSdkStyleEvent(e0, "PostBuild", "AfterTargets", "PostBuildEvent",
4916 this->GeneratorTarget->GetPostBuildCommands(),
4917 configName);
4920 void cmVisualStudio10TargetGenerator::WriteSdkStyleEvent(
4921 Elem& e0, const std::string& name, const std::string& when,
4922 const std::string& target, std::vector<cmCustomCommand> const& commands,
4923 std::string const& configName)
4925 if (commands.empty()) {
4926 return;
4928 Elem e1(e0, "Target");
4929 e1.Attribute("Condition",
4930 cmStrCat("'$(Configuration)' == '", configName, '\''));
4931 e1.Attribute("Name", name + configName);
4932 e1.Attribute(when.c_str(), target);
4933 e1.SetHasElements();
4935 cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
4936 std::string script;
4937 const char* pre = "";
4938 std::string comment;
4939 bool stdPipesUTF8 = false;
4940 for (cmCustomCommand const& cc : commands) {
4941 cmCustomCommandGenerator ccg(cc, configName, lg);
4942 if (!ccg.HasOnlyEmptyCommandLines()) {
4943 comment += pre;
4944 comment += lg->ConstructComment(ccg);
4945 script += pre;
4946 pre = "\n";
4947 script += lg->ConstructScript(ccg);
4949 stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
4952 if (!script.empty()) {
4953 script += lg->FinishConstructScript(this->ProjectType);
4955 comment = cmVS10EscapeComment(comment);
4957 std::string strippedComment = comment;
4958 strippedComment.erase(
4959 std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
4960 strippedComment.end());
4961 std::ostringstream oss;
4962 if (!comment.empty() && !strippedComment.empty()) {
4963 oss << "echo " << comment << "\n";
4965 oss << script << "\n";
4967 Elem e2(e1, "Exec");
4968 e2.Attribute("Command", oss.str());
4971 void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0)
4973 cmGlobalGenerator::TargetDependSet const& unordered =
4974 this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
4975 using OrderedTargetDependSet =
4976 cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
4977 OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
4978 Elem e1(e0, "ItemGroup");
4979 e1.SetHasElements();
4980 for (cmGeneratorTarget const* dt : depends) {
4981 if (!dt->IsInBuildSystem()) {
4982 continue;
4984 // skip fortran targets as they can not be processed by MSBuild
4985 // the only reference will be in the .sln file
4986 if (this->GlobalGenerator->TargetIsFortranOnly(dt)) {
4987 continue;
4989 cmLocalGenerator* lg = dt->GetLocalGenerator();
4990 std::string name = dt->GetName();
4991 std::string path;
4992 if (cmValue p = dt->GetProperty("EXTERNAL_MSPROJECT")) {
4993 path = *p;
4994 } else {
4995 path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(),
4996 computeProjectFileExtension(dt));
4998 ConvertToWindowsSlash(path);
4999 Elem e2(e1, "ProjectReference");
5000 e2.Attribute("Include", path);
5001 e2.Element("Project",
5002 cmStrCat('{', this->GlobalGenerator->GetGUID(name), '}'));
5003 e2.Element("Name", name);
5004 this->WriteDotNetReferenceCustomTags(e2, name);
5005 if (dt->IsCSharpOnly() || cmHasLiteralSuffix(path, "csproj")) {
5006 e2.Element("SkipGetTargetFrameworkProperties", "true");
5008 // Don't reference targets that don't produce any output.
5009 else if (this->Configurations.empty() ||
5010 dt->GetManagedType(this->Configurations[0]) ==
5011 cmGeneratorTarget::ManagedType::Undefined) {
5012 e2.Element("ReferenceOutputAssembly", "false");
5013 e2.Element("CopyToOutputDirectory", "Never");
5018 void cmVisualStudio10TargetGenerator::WritePlatformExtensions(Elem& e1)
5020 // This only applies to Windows 10 apps
5021 if (this->GlobalGenerator->TargetsWindowsStore() &&
5022 cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
5023 cmValue desktopExtensionsVersion =
5024 this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
5025 if (desktopExtensionsVersion) {
5026 this->WriteSinglePlatformExtension(e1, "WindowsDesktop",
5027 *desktopExtensionsVersion);
5029 cmValue mobileExtensionsVersion =
5030 this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
5031 if (mobileExtensionsVersion) {
5032 this->WriteSinglePlatformExtension(e1, "WindowsMobile",
5033 *mobileExtensionsVersion);
5038 void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
5039 Elem& e1, std::string const& extension, std::string const& version)
5041 const std::string s =
5042 cmStrCat("$([Microsoft.Build.Utilities.ToolLocationHelper]"
5043 "::GetPlatformExtensionSDKLocation(`",
5044 extension, ", Version=", version,
5045 "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
5046 "$(ExtensionSDKDirectoryRoot), null))"
5047 "\\DesignTime\\CommonConfiguration\\Neutral\\",
5048 extension, ".props");
5050 Elem e2(e1, "Import");
5051 e2.Attribute("Project", s);
5052 e2.Attribute("Condition", cmStrCat("exists('", s, "')"));
5055 void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0)
5057 cmList sdkReferences;
5058 std::unique_ptr<Elem> spe1;
5059 if (cmValue vsSDKReferences =
5060 this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
5061 sdkReferences.assign(*vsSDKReferences);
5062 spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
5063 for (auto const& ri : sdkReferences) {
5064 Elem(*spe1, "SDKReference").Attribute("Include", ri);
5068 // This only applies to Windows 10 apps
5069 if (this->GlobalGenerator->TargetsWindowsStore() &&
5070 cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
5071 cmValue desktopExtensionsVersion =
5072 this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
5073 cmValue mobileExtensionsVersion =
5074 this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
5075 cmValue iotExtensionsVersion =
5076 this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
5078 if (desktopExtensionsVersion || mobileExtensionsVersion ||
5079 iotExtensionsVersion) {
5080 if (!spe1) {
5081 spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
5083 if (desktopExtensionsVersion) {
5084 this->WriteSingleSDKReference(*spe1, "WindowsDesktop",
5085 *desktopExtensionsVersion);
5087 if (mobileExtensionsVersion) {
5088 this->WriteSingleSDKReference(*spe1, "WindowsMobile",
5089 *mobileExtensionsVersion);
5091 if (iotExtensionsVersion) {
5092 this->WriteSingleSDKReference(*spe1, "WindowsIoT",
5093 *iotExtensionsVersion);
5099 void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
5100 Elem& e1, std::string const& extension, std::string const& version)
5102 Elem(e1, "SDKReference")
5103 .Attribute("Include", cmStrCat(extension, ", Version=", version));
5106 namespace {
5107 std::string ComputeCertificateThumbprint(const std::string& source)
5109 std::string thumbprint;
5111 CRYPT_INTEGER_BLOB cryptBlob;
5112 HCERTSTORE certStore = nullptr;
5113 PCCERT_CONTEXT certContext = nullptr;
5115 HANDLE certFile = CreateFileW(
5116 cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
5117 FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
5119 if (certFile != INVALID_HANDLE_VALUE && certFile) {
5120 DWORD fileSize = GetFileSize(certFile, nullptr);
5121 if (fileSize != INVALID_FILE_SIZE) {
5122 auto certData = cm::make_unique<BYTE[]>(fileSize);
5123 if (certData) {
5124 DWORD dwRead = 0;
5125 if (ReadFile(certFile, certData.get(), fileSize, &dwRead, nullptr)) {
5126 cryptBlob.cbData = fileSize;
5127 cryptBlob.pbData = certData.get();
5129 // Verify that this is a valid cert
5130 if (PFXIsPFXBlob(&cryptBlob)) {
5131 // Open the certificate as a store
5132 certStore =
5133 PFXImportCertStore(&cryptBlob, nullptr, CRYPT_EXPORTABLE);
5134 if (certStore) {
5135 // There should only be 1 cert.
5136 certContext =
5137 CertEnumCertificatesInStore(certStore, certContext);
5138 if (certContext) {
5139 // The hash is 20 bytes
5140 BYTE hashData[20];
5141 DWORD hashLength = 20;
5143 // Buffer to print the hash. Each byte takes 2 chars +
5144 // terminating character
5145 char hashPrint[41];
5146 char* pHashPrint = hashPrint;
5147 // Get the hash property from the certificate
5148 if (CertGetCertificateContextProperty(
5149 certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
5150 for (DWORD i = 0; i < hashLength; i++) {
5151 // Convert each byte to hexadecimal
5152 snprintf(pHashPrint, 3, "%02X", hashData[i]);
5153 pHashPrint += 2;
5155 *pHashPrint = '\0';
5156 thumbprint = hashPrint;
5158 CertFreeCertificateContext(certContext);
5160 CertCloseStore(certStore, 0);
5166 CloseHandle(certFile);
5169 return thumbprint;
5173 void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile(
5174 Elem& e0)
5176 if ((this->GlobalGenerator->TargetsWindowsStore() ||
5177 this->GlobalGenerator->TargetsWindowsPhone()) &&
5178 (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
5179 std::string pfxFile;
5180 for (cmGeneratorTarget::AllConfigSource const& source :
5181 this->GeneratorTarget->GetAllConfigSources()) {
5182 if (source.Kind == cmGeneratorTarget::SourceKindCertificate) {
5183 pfxFile = this->ConvertPath(source.Source->GetFullPath(), false);
5184 ConvertToWindowsSlash(pfxFile);
5185 break;
5189 if (this->IsMissingFiles &&
5190 !(this->GlobalGenerator->TargetsWindowsPhone() &&
5191 this->GlobalGenerator->GetSystemVersion() == "8.0"_s)) {
5192 // Move the manifest to a project directory to avoid clashes
5193 std::string artifactDir =
5194 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5195 ConvertToWindowsSlash(artifactDir);
5196 Elem e1(e0, "PropertyGroup");
5197 e1.Element("AppxPackageArtifactsDir", cmStrCat(artifactDir, '\\'));
5198 std::string resourcePriFile =
5199 cmStrCat(this->DefaultArtifactDir, "/resources.pri");
5200 ConvertToWindowsSlash(resourcePriFile);
5201 e1.Element("ProjectPriFullPath", resourcePriFile);
5203 // If we are missing files and we don't have a certificate and
5204 // aren't targeting WP8.0, add a default certificate
5205 if (pfxFile.empty()) {
5206 std::string templateFolder =
5207 cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
5208 pfxFile =
5209 cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
5210 cmSystemTools::CopyAFile(
5211 cmStrCat(templateFolder, "/Windows_TemporaryKey.pfx"), pfxFile,
5212 false);
5213 ConvertToWindowsSlash(pfxFile);
5214 this->AddedFiles.push_back(pfxFile);
5215 this->AddedDefaultCertificate = true;
5218 e1.Element("PackageCertificateKeyFile", pfxFile);
5219 std::string thumb = ComputeCertificateThumbprint(pfxFile);
5220 if (!thumb.empty()) {
5221 e1.Element("PackageCertificateThumbprint", thumb);
5223 } else if (!pfxFile.empty()) {
5224 Elem e1(e0, "PropertyGroup");
5225 e1.Element("PackageCertificateKeyFile", pfxFile);
5226 std::string thumb = ComputeCertificateThumbprint(pfxFile);
5227 if (!thumb.empty()) {
5228 e1.Element("PackageCertificateThumbprint", thumb);
5234 void cmVisualStudio10TargetGenerator::ClassifyAllConfigSources()
5236 for (cmGeneratorTarget::AllConfigSource const& source :
5237 this->GeneratorTarget->GetAllConfigSources()) {
5238 this->ClassifyAllConfigSource(source);
5242 void cmVisualStudio10TargetGenerator::ClassifyAllConfigSource(
5243 cmGeneratorTarget::AllConfigSource const& acs)
5245 switch (acs.Kind) {
5246 case cmGeneratorTarget::SourceKindResx: {
5247 // Build and save the name of the corresponding .h file
5248 // This relationship will be used later when building the project files.
5249 // Both names would have been auto generated from Visual Studio
5250 // where the user supplied the file name and Visual Studio
5251 // appended the suffix.
5252 std::string resx = acs.Source->ResolveFullPath();
5253 std::string hFileName =
5254 cmStrCat(resx.substr(0, resx.find_last_of('.')), ".h");
5255 this->ExpectedResxHeaders.insert(hFileName);
5256 } break;
5257 case cmGeneratorTarget::SourceKindXaml: {
5258 // Build and save the name of the corresponding .h and .cpp file
5259 // This relationship will be used later when building the project files.
5260 // Both names would have been auto generated from Visual Studio
5261 // where the user supplied the file name and Visual Studio
5262 // appended the suffix.
5263 std::string xaml = acs.Source->ResolveFullPath();
5264 std::string hFileName = cmStrCat(xaml, ".h");
5265 std::string cppFileName = cmStrCat(xaml, ".cpp");
5266 this->ExpectedXamlHeaders.insert(hFileName);
5267 this->ExpectedXamlSources.insert(cppFileName);
5268 } break;
5269 default:
5270 break;
5274 bool cmVisualStudio10TargetGenerator::IsResxHeader(
5275 const std::string& headerFile)
5277 return this->ExpectedResxHeaders.count(headerFile) > 0;
5280 bool cmVisualStudio10TargetGenerator::IsXamlHeader(
5281 const std::string& headerFile)
5283 return this->ExpectedXamlHeaders.count(headerFile) > 0;
5286 bool cmVisualStudio10TargetGenerator::IsXamlSource(
5287 const std::string& sourceFile)
5289 return this->ExpectedXamlSources.count(sourceFile) > 0;
5292 void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1)
5294 cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
5295 bool isAppContainer = false;
5296 bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
5297 bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
5298 bool const isAndroid = this->GlobalGenerator->TargetsAndroid();
5299 std::string const& rev = this->GlobalGenerator->GetApplicationTypeRevision();
5300 if (isWindowsPhone || isWindowsStore) {
5301 e1.Element("ApplicationType",
5302 (isWindowsPhone ? "Windows Phone" : "Windows Store"));
5303 e1.Element("DefaultLanguage", "en-US");
5304 if (rev == "10.0"_s) {
5305 e1.Element("ApplicationTypeRevision", rev);
5306 // Visual Studio 14.0 is necessary for building 10.0 apps
5307 e1.Element("MinimumVisualStudioVersion", "14.0");
5309 if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
5310 isAppContainer = true;
5312 } else if (rev == "8.1"_s) {
5313 e1.Element("ApplicationTypeRevision", rev);
5314 // Visual Studio 12.0 is necessary for building 8.1 apps
5315 e1.Element("MinimumVisualStudioVersion", "12.0");
5317 if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
5318 isAppContainer = true;
5320 } else if (rev == "8.0"_s) {
5321 e1.Element("ApplicationTypeRevision", rev);
5322 // Visual Studio 11.0 is necessary for building 8.0 apps
5323 e1.Element("MinimumVisualStudioVersion", "11.0");
5325 if (isWindowsStore &&
5326 this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
5327 isAppContainer = true;
5328 } else if (isWindowsPhone &&
5329 this->GeneratorTarget->GetType() ==
5330 cmStateEnums::EXECUTABLE) {
5331 e1.Element("XapOutputs", "true");
5332 e1.Element("XapFilename",
5333 cmStrCat(this->Name, "_$(Configuration)_$(Platform).xap"));
5336 } else if (isAndroid) {
5337 e1.Element("ApplicationType", "Android");
5338 e1.Element("ApplicationTypeRevision",
5339 gg->GetAndroidApplicationTypeRevision());
5341 if (isAppContainer) {
5342 e1.Element("AppContainerApplication", "true");
5343 } else if (!isAndroid) {
5344 if (this->Platform == "ARM64"_s) {
5345 e1.Element("WindowsSDKDesktopARM64Support", "true");
5346 } else if (this->Platform == "ARM"_s) {
5347 e1.Element("WindowsSDKDesktopARMSupport", "true");
5350 std::string const& targetPlatformVersion =
5351 gg->GetWindowsTargetPlatformVersion();
5352 if (!targetPlatformVersion.empty()) {
5353 e1.Element("WindowsTargetPlatformVersion", targetPlatformVersion);
5355 cmValue targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
5356 "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
5357 if (targetPlatformMinVersion) {
5358 e1.Element("WindowsTargetPlatformMinVersion", *targetPlatformMinVersion);
5359 } else if (isWindowsStore && rev == "10.0"_s) {
5360 // If the min version is not set, then use the TargetPlatformVersion
5361 if (!targetPlatformVersion.empty()) {
5362 e1.Element("WindowsTargetPlatformMinVersion", targetPlatformVersion);
5366 // Added IoT Startup Task support
5367 if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
5368 e1.Element("ContainsStartupTask", "true");
5372 void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
5374 // For Windows and Windows Phone executables, we will assume that if a
5375 // manifest is not present that we need to add all the necessary files
5376 if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
5377 std::vector<cmGeneratorTarget::AllConfigSource> manifestSources =
5378 this->GeneratorTarget->GetAllConfigSources(
5379 cmGeneratorTarget::SourceKindAppManifest);
5380 std::string const& v = this->GlobalGenerator->GetSystemVersion();
5381 if (this->GlobalGenerator->TargetsWindowsPhone()) {
5382 if (v == "8.0"_s) {
5383 // Look through the sources for WMAppManifest.xml
5384 bool foundManifest = false;
5385 for (cmGeneratorTarget::AllConfigSource const& source :
5386 this->GeneratorTarget->GetAllConfigSources()) {
5387 if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
5388 "wmappmanifest.xml" ==
5389 cmSystemTools::LowerCase(
5390 source.Source->GetLocation().GetName())) {
5391 foundManifest = true;
5392 break;
5395 if (!foundManifest) {
5396 this->IsMissingFiles = true;
5398 } else if (v == "8.1"_s) {
5399 if (manifestSources.empty()) {
5400 this->IsMissingFiles = true;
5403 } else if (this->GlobalGenerator->TargetsWindowsStore()) {
5404 if (manifestSources.empty()) {
5405 if (v == "8.0"_s) {
5406 this->IsMissingFiles = true;
5407 } else if (v == "8.1"_s || cmHasLiteralPrefix(v, "10.0")) {
5408 this->IsMissingFiles = true;
5415 void cmVisualStudio10TargetGenerator::WriteMissingFiles(Elem& e1)
5417 std::string const& v = this->GlobalGenerator->GetSystemVersion();
5418 if (this->GlobalGenerator->TargetsWindowsPhone()) {
5419 if (v == "8.0"_s) {
5420 this->WriteMissingFilesWP80(e1);
5421 } else if (v == "8.1"_s) {
5422 this->WriteMissingFilesWP81(e1);
5424 } else if (this->GlobalGenerator->TargetsWindowsStore()) {
5425 if (v == "8.0"_s) {
5426 this->WriteMissingFilesWS80(e1);
5427 } else if (v == "8.1"_s) {
5428 this->WriteMissingFilesWS81(e1);
5429 } else if (cmHasLiteralPrefix(v, "10.0")) {
5430 this->WriteMissingFilesWS10_0(e1);
5435 void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80(Elem& e1)
5437 std::string templateFolder =
5438 cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
5440 // For WP80, the manifest needs to be in the same folder as the project
5441 // this can cause an overwrite problem if projects aren't organized in
5442 // folders
5443 std::string manifestFile = cmStrCat(
5444 this->LocalGenerator->GetCurrentBinaryDirectory(), "/WMAppManifest.xml");
5445 std::string artifactDir =
5446 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5447 ConvertToWindowsSlash(artifactDir);
5448 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5449 const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
5451 cmGeneratedFileStream fout(manifestFile);
5452 fout.SetCopyIfDifferent(true);
5454 /* clang-format off */
5455 fout <<
5456 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5457 "<Deployment"
5458 " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
5459 " AppPlatformVersion=\"8.0\">\n"
5460 "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
5461 "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
5462 " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
5463 " Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"CMake\""
5464 " Description=\"Default CMake App\" Publisher=\"CMake\""
5465 " PublisherID=\"{" << this->GUID << "}\">\n"
5466 "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
5467 << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
5468 "\t\t<Capabilities/>\n"
5469 "\t\t<Tasks>\n"
5470 "\t\t\t<DefaultTask Name=\"_default\""
5471 " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
5472 "\t\t</Tasks>\n"
5473 "\t\t<Tokens>\n"
5474 "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
5475 " TaskName=\"_default\">\n"
5476 "\t\t\t\t<TemplateFlip>\n"
5477 "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
5478 << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
5479 "\t\t\t\t\t<Count>0</Count>\n"
5480 "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
5481 << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
5482 "\t\t\t\t</TemplateFlip>\n"
5483 "\t\t\t</PrimaryToken>\n"
5484 "\t\t</Tokens>\n"
5485 "\t\t<ScreenResolutions>\n"
5486 "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
5487 "\t\t</ScreenResolutions>\n"
5488 "\t</App>\n"
5489 "</Deployment>\n";
5490 /* clang-format on */
5492 std::string sourceFile = this->ConvertPath(manifestFile, false);
5493 ConvertToWindowsSlash(sourceFile);
5495 Elem e2(e1, "Xml");
5496 e2.Attribute("Include", sourceFile);
5497 e2.Element("SubType", "Designer");
5499 this->AddedFiles.push_back(sourceFile);
5501 std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
5502 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
5503 smallLogo, false);
5504 ConvertToWindowsSlash(smallLogo);
5505 Elem(e1, "Image").Attribute("Include", smallLogo);
5506 this->AddedFiles.push_back(smallLogo);
5508 std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
5509 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
5510 ConvertToWindowsSlash(logo);
5511 Elem(e1, "Image").Attribute("Include", logo);
5512 this->AddedFiles.push_back(logo);
5514 std::string applicationIcon =
5515 cmStrCat(this->DefaultArtifactDir, "/ApplicationIcon.png");
5516 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/ApplicationIcon.png"),
5517 applicationIcon, false);
5518 ConvertToWindowsSlash(applicationIcon);
5519 Elem(e1, "Image").Attribute("Include", applicationIcon);
5520 this->AddedFiles.push_back(applicationIcon);
5523 void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81(Elem& e1)
5525 std::string manifestFile =
5526 cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
5527 std::string artifactDir =
5528 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5529 ConvertToWindowsSlash(artifactDir);
5530 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5531 const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
5533 cmGeneratedFileStream fout(manifestFile);
5534 fout.SetCopyIfDifferent(true);
5536 /* clang-format off */
5537 fout <<
5538 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5539 "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
5540 " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
5541 " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
5542 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5543 " Version=\"1.0.0.0\" />\n"
5544 "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
5545 " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
5546 "\t<Properties>\n"
5547 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5548 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5549 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5550 "\t</Properties>\n"
5551 "\t<Prerequisites>\n"
5552 "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
5553 "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
5554 "\t</Prerequisites>\n"
5555 "\t<Resources>\n"
5556 "\t\t<Resource Language=\"x-generate\" />\n"
5557 "\t</Resources>\n"
5558 "\t<Applications>\n"
5559 "\t\t<Application Id=\"App\""
5560 " Executable=\"" << targetNameXML << ".exe\""
5561 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5562 "\t\t\t<m2:VisualElements\n"
5563 "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5564 "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5565 "\t\t\t\tBackgroundColor=\"#336699\"\n"
5566 "\t\t\t\tForegroundText=\"light\"\n"
5567 "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5568 "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5569 "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
5570 "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
5571 "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
5572 "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
5573 "\t\t\t\t</m2:DefaultTile>\n"
5574 "\t\t\t\t<m2:SplashScreen"
5575 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5576 "\t\t\t</m2:VisualElements>\n"
5577 "\t\t</Application>\n"
5578 "\t</Applications>\n"
5579 "</Package>\n";
5580 /* clang-format on */
5582 this->WriteCommonMissingFiles(e1, manifestFile);
5585 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80(Elem& e1)
5587 std::string manifestFile =
5588 cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
5589 std::string artifactDir =
5590 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5591 ConvertToWindowsSlash(artifactDir);
5592 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5593 const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
5595 cmGeneratedFileStream fout(manifestFile);
5596 fout.SetCopyIfDifferent(true);
5598 /* clang-format off */
5599 fout <<
5600 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5601 "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
5602 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5603 " Version=\"1.0.0.0\" />\n"
5604 "\t<Properties>\n"
5605 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5606 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5607 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5608 "\t</Properties>\n"
5609 "\t<Prerequisites>\n"
5610 "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
5611 "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
5612 "\t</Prerequisites>\n"
5613 "\t<Resources>\n"
5614 "\t\t<Resource Language=\"x-generate\" />\n"
5615 "\t</Resources>\n"
5616 "\t<Applications>\n"
5617 "\t\t<Application Id=\"App\""
5618 " Executable=\"" << targetNameXML << ".exe\""
5619 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5620 "\t\t\t<VisualElements"
5621 " DisplayName=\"" << targetNameXML << "\""
5622 " Description=\"" << targetNameXML << "\""
5623 " BackgroundColor=\"#336699\" ForegroundText=\"light\""
5624 " Logo=\"" << artifactDirXML << "\\Logo.png\""
5625 " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5626 "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
5627 " ShortName=\"" << targetNameXML << "\" />\n"
5628 "\t\t\t\t<SplashScreen"
5629 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5630 "\t\t\t</VisualElements>\n"
5631 "\t\t</Application>\n"
5632 "\t</Applications>\n"
5633 "</Package>\n";
5634 /* clang-format on */
5636 this->WriteCommonMissingFiles(e1, manifestFile);
5639 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81(Elem& e1)
5641 std::string manifestFile =
5642 cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
5643 std::string artifactDir =
5644 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5645 ConvertToWindowsSlash(artifactDir);
5646 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5647 const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
5649 cmGeneratedFileStream fout(manifestFile);
5650 fout.SetCopyIfDifferent(true);
5652 /* clang-format off */
5653 fout <<
5654 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5655 "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
5656 " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
5657 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5658 " Version=\"1.0.0.0\" />\n"
5659 "\t<Properties>\n"
5660 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5661 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5662 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5663 "\t</Properties>\n"
5664 "\t<Prerequisites>\n"
5665 "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
5666 "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
5667 "\t</Prerequisites>\n"
5668 "\t<Resources>\n"
5669 "\t\t<Resource Language=\"x-generate\" />\n"
5670 "\t</Resources>\n"
5671 "\t<Applications>\n"
5672 "\t\t<Application Id=\"App\""
5673 " Executable=\"" << targetNameXML << ".exe\""
5674 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5675 "\t\t\t<m2:VisualElements\n"
5676 "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5677 "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5678 "\t\t\t\tBackgroundColor=\"#336699\"\n"
5679 "\t\t\t\tForegroundText=\"light\"\n"
5680 "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5681 "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5682 "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
5683 "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
5684 "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
5685 "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
5686 "\t\t\t\t</m2:DefaultTile>\n"
5687 "\t\t\t\t<m2:SplashScreen"
5688 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5689 "\t\t\t</m2:VisualElements>\n"
5690 "\t\t</Application>\n"
5691 "\t</Applications>\n"
5692 "</Package>\n";
5693 /* clang-format on */
5695 this->WriteCommonMissingFiles(e1, manifestFile);
5698 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0(Elem& e1)
5700 std::string manifestFile =
5701 cmStrCat(this->DefaultArtifactDir, "/package.appxManifest");
5702 std::string artifactDir =
5703 this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5704 ConvertToWindowsSlash(artifactDir);
5705 std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5706 const std::string& targetNameXML = cmVS10EscapeXML(GetTargetOutputName());
5708 cmGeneratedFileStream fout(manifestFile);
5709 fout.SetCopyIfDifferent(true);
5711 /* clang-format off */
5712 fout <<
5713 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5714 "<Package\n\t"
5715 "xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
5716 "\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
5717 "\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
5718 "\n\tIgnorableNamespaces=\"uap mp\">\n\n"
5719 "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5720 " Version=\"1.0.0.0\" />\n"
5721 "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
5722 "\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
5723 "\t<Properties>\n"
5724 "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5725 "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5726 "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5727 "\t</Properties>\n"
5728 "\t<Dependencies>\n"
5729 "\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
5730 "MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
5731 "\t</Dependencies>\n"
5733 "\t<Resources>\n"
5734 "\t\t<Resource Language=\"x-generate\" />\n"
5735 "\t</Resources>\n"
5736 "\t<Applications>\n"
5737 "\t\t<Application Id=\"App\""
5738 " Executable=\"" << targetNameXML << ".exe\""
5739 " EntryPoint=\"" << targetNameXML << ".App\">\n"
5740 "\t\t\t<uap:VisualElements\n"
5741 "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5742 "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5743 "\t\t\t\tBackgroundColor=\"#336699\"\n"
5744 "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5745 "\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
5746 "\\SmallLogo44x44.png\">\n"
5747 "\t\t\t\t<uap:SplashScreen"
5748 " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5749 "\t\t\t</uap:VisualElements>\n"
5750 "\t\t</Application>\n"
5751 "\t</Applications>\n"
5752 "</Package>\n";
5753 /* clang-format on */
5755 this->WriteCommonMissingFiles(e1, manifestFile);
5758 void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
5759 Elem& e1, const std::string& manifestFile)
5761 std::string templateFolder =
5762 cmStrCat(cmSystemTools::GetCMakeRoot(), "/Templates/Windows");
5764 std::string sourceFile = this->ConvertPath(manifestFile, false);
5765 ConvertToWindowsSlash(sourceFile);
5767 Elem e2(e1, "AppxManifest");
5768 e2.Attribute("Include", sourceFile);
5769 e2.Element("SubType", "Designer");
5771 this->AddedFiles.push_back(sourceFile);
5773 std::string smallLogo = cmStrCat(this->DefaultArtifactDir, "/SmallLogo.png");
5774 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo.png"),
5775 smallLogo, false);
5776 ConvertToWindowsSlash(smallLogo);
5777 Elem(e1, "Image").Attribute("Include", smallLogo);
5778 this->AddedFiles.push_back(smallLogo);
5780 std::string smallLogo44 =
5781 cmStrCat(this->DefaultArtifactDir, "/SmallLogo44x44.png");
5782 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SmallLogo44x44.png"),
5783 smallLogo44, false);
5784 ConvertToWindowsSlash(smallLogo44);
5785 Elem(e1, "Image").Attribute("Include", smallLogo44);
5786 this->AddedFiles.push_back(smallLogo44);
5788 std::string logo = cmStrCat(this->DefaultArtifactDir, "/Logo.png");
5789 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/Logo.png"), logo, false);
5790 ConvertToWindowsSlash(logo);
5791 Elem(e1, "Image").Attribute("Include", logo);
5792 this->AddedFiles.push_back(logo);
5794 std::string storeLogo = cmStrCat(this->DefaultArtifactDir, "/StoreLogo.png");
5795 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/StoreLogo.png"),
5796 storeLogo, false);
5797 ConvertToWindowsSlash(storeLogo);
5798 Elem(e1, "Image").Attribute("Include", storeLogo);
5799 this->AddedFiles.push_back(storeLogo);
5801 std::string splashScreen =
5802 cmStrCat(this->DefaultArtifactDir, "/SplashScreen.png");
5803 cmSystemTools::CopyAFile(cmStrCat(templateFolder, "/SplashScreen.png"),
5804 splashScreen, false);
5805 ConvertToWindowsSlash(splashScreen);
5806 Elem(e1, "Image").Attribute("Include", splashScreen);
5807 this->AddedFiles.push_back(splashScreen);
5809 if (this->AddedDefaultCertificate) {
5810 // This file has already been added to the build so don't copy it
5811 std::string keyFile =
5812 cmStrCat(this->DefaultArtifactDir, "/Windows_TemporaryKey.pfx");
5813 ConvertToWindowsSlash(keyFile);
5814 Elem(e1, "None").Attribute("Include", keyFile);
5818 bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
5820 HANDLE h =
5821 CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
5822 FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
5823 FILE_FLAG_BACKUP_SEMANTICS, 0);
5824 if (!h) {
5825 return false;
5828 FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
5829 if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
5830 CloseHandle(h);
5831 return false;
5834 CloseHandle(h);
5835 return true;
5838 void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
5839 cmSourceFile const* sf, std::map<std::string, std::string>& tags)
5841 if (this->ProjectType == VsProjectType::csproj) {
5842 const cmPropertyMap& props = sf->GetProperties();
5843 for (const std::string& p : props.GetKeys()) {
5844 static const cm::string_view propNamePrefix = "VS_CSHARP_";
5845 if (cmHasPrefix(p, propNamePrefix)) {
5846 std::string tagName = p.substr(propNamePrefix.length());
5847 if (!tagName.empty()) {
5848 cmValue val = props.GetPropertyValue(p);
5849 if (cmNonempty(val)) {
5850 tags[tagName] = *val;
5851 } else {
5852 tags.erase(tagName);
5860 void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
5861 Elem& e2, const std::map<std::string, std::string>& tags)
5863 for (const auto& i : tags) {
5864 e2.Element(i.first, i.second);
5868 std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
5869 cmSourceFile const* source)
5871 // For out of source files, we first check if a matching source group
5872 // for this file exists, otherwise we check if the path relative to current
5873 // source- or binary-dir is used within the link and return that.
5874 // In case of .cs files we can't do that automatically for files in the
5875 // binary directory, because this leads to compilation errors.
5876 std::string link;
5877 std::string sourceGroupedFile;
5878 std::string const& fullFileName = source->GetFullPath();
5879 std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory();
5880 std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory();
5881 // unfortunately we have to copy the source groups, because
5882 // FindSourceGroup uses a regex which is modifying the group
5883 std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
5884 cmSourceGroup* sourceGroup =
5885 this->Makefile->FindSourceGroup(fullFileName, sourceGroups);
5886 if (sourceGroup && !sourceGroup->GetFullName().empty()) {
5887 sourceGroupedFile =
5888 cmStrCat(sourceGroup->GetFullName(), '/',
5889 cmsys::SystemTools::GetFilenameName(fullFileName));
5890 cmsys::SystemTools::ConvertToUnixSlashes(sourceGroupedFile);
5893 if (!sourceGroupedFile.empty() &&
5894 cmHasSuffix(fullFileName, sourceGroupedFile)) {
5895 link = sourceGroupedFile;
5896 } else if (cmHasPrefix(fullFileName, srcDir)) {
5897 link = fullFileName.substr(srcDir.length() + 1);
5898 } else if (!cmHasSuffix(fullFileName, ".cs") &&
5899 cmHasPrefix(fullFileName, binDir)) {
5900 link = fullFileName.substr(binDir.length() + 1);
5901 } else if (cmValue l = source->GetProperty("VS_CSHARP_Link")) {
5902 link = *l;
5905 ConvertToWindowsSlash(link);
5906 return link;
5909 std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
5910 const char* relativeFilePath) const
5912 // Always search in the standard modules location.
5913 std::string path =
5914 cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath);
5915 ConvertToWindowsSlash(path);
5917 return path;
5920 void cmVisualStudio10TargetGenerator::WriteStdOutEncodingUtf8(Elem& e1)
5922 if (this->GlobalGenerator->IsUtf8EncodingSupported()) {
5923 e1.Element("UseUtf8Encoding", "Always");
5924 } else if (this->GlobalGenerator->IsStdOutEncodingSupported()) {
5925 e1.Element("StdOutEncoding", "UTF-8");
5929 void cmVisualStudio10TargetGenerator::UpdateCache()
5931 std::vector<std::string> packageReferences;
5933 if (this->GeneratorTarget->IsDotNetSdkTarget() ||
5934 this->GeneratorTarget->HasPackageReferences()) {
5935 // Store a cache entry that later determines, if a package restore is
5936 // required.
5937 this->GeneratorTarget->Makefile->AddCacheDefinition(
5938 cmStrCat(this->GeneratorTarget->GetName(),
5939 "_REQUIRES_VS_PACKAGE_RESTORE"),
5940 "ON", "Value Computed by CMake", cmStateEnums::STATIC);
5941 } else {
5942 // If there are any dependencies that require package restore, inherit the
5943 // cache variable.
5944 cmGlobalGenerator::TargetDependSet const& unordered =
5945 this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
5946 using OrderedTargetDependSet =
5947 cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
5948 OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
5950 for (cmGeneratorTarget const* dt : depends) {
5951 if (dt->IsDotNetSdkTarget() || dt->HasPackageReferences()) {
5952 this->GeneratorTarget->Makefile->AddCacheDefinition(
5953 cmStrCat(this->GeneratorTarget->GetName(),
5954 "_REQUIRES_VS_PACKAGE_RESTORE"),
5955 "ON", "Value Computed by CMake", cmStateEnums::STATIC);