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 "cmLocalGenerator.h"
10 #include <initializer_list>
13 #include <unordered_set>
18 #include <cm/optional>
19 #include <cm/string_view>
20 #include <cmext/algorithm>
21 #include <cmext/string_view>
23 #include "cmsys/RegularExpression.hxx"
25 #include "cmAlgorithms.h"
26 #include "cmComputeLinkInformation.h"
27 #include "cmCustomCommand.h"
28 #include "cmCustomCommandGenerator.h"
29 #include "cmCustomCommandLines.h"
30 #include "cmCustomCommandTypes.h"
31 #include "cmGeneratedFileStream.h"
32 #include "cmGeneratorExpression.h"
33 #include "cmGeneratorExpressionEvaluationFile.h"
34 #include "cmGeneratorTarget.h"
35 #include "cmGlobalGenerator.h"
36 #include "cmInstallGenerator.h"
37 #include "cmInstallScriptGenerator.h"
38 #include "cmInstallTargetGenerator.h"
39 #include "cmLinkLineComputer.h"
40 #include "cmLinkLineDeviceComputer.h"
41 #include "cmMakefile.h"
43 #include "cmRulePlaceholderExpander.h"
44 #include "cmSourceFile.h"
45 #include "cmSourceFileLocation.h"
46 #include "cmSourceFileLocationKind.h"
47 #include "cmStandardLevelResolver.h"
49 #include "cmStateDirectory.h"
50 #include "cmStateTypes.h"
51 #include "cmStringAlgorithms.h"
52 #include "cmSystemTools.h"
54 #include "cmTestGenerator.h"
56 #include "cmVersion.h"
59 #if !defined(CMAKE_BOOTSTRAP)
60 # define CM_LG_ENCODE_OBJECT_NAMES
61 # include "cmCryptoHash.h"
64 #if defined(__HAIKU__)
65 # include <FindDirectory.h>
66 # include <StorageDefs.h>
69 // List of variables that are replaced when
70 // rules are expanced. These variables are
71 // replaced in the form <var> with GetSafeDefinition(var).
72 // ${LANG} is replaced in the variable first with all enabled
74 static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
75 "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
76 "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
77 "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
78 "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
79 "CMAKE_${LANG}_LINK_FLAGS",
80 "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
81 "CMAKE_${LANG}_ARCHIVE",
83 "CMAKE_CURRENT_SOURCE_DIR",
84 "CMAKE_CURRENT_BINARY_DIR",
88 "CMAKE_CUDA_HOST_COMPILER",
89 "CMAKE_CUDA_HOST_LINK_LAUNCHER",
90 "CMAKE_CL_SHOWINCLUDES_PREFIX" };
92 cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
93 : cmOutputConverter(makefile->GetStateSnapshot())
94 , DirectoryBacktrace(makefile->GetBacktrace())
96 this->GlobalGenerator = gg;
98 this->Makefile = makefile;
100 this->AliasTargets = makefile->GetAliasTargets();
102 this->EmitUniversalBinaryFlags = true;
103 this->BackwardsCompatibility = 0;
104 this->BackwardsCompatibilityFinal = false;
106 this->ComputeObjectMaxPath();
108 // Canonicalize entries of the CPATH environment variable the same
109 // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
111 std::vector<std::string> cpath;
112 cmSystemTools::GetPath(cpath, "CPATH");
113 for (std::string const& cp : cpath) {
114 if (cmSystemTools::FileIsFullPath(cp)) {
115 this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
120 std::vector<std::string> enabledLanguages =
121 this->GetState()->GetEnabledLanguages();
123 if (cmValue sysrootCompile =
124 this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
125 this->CompilerSysroot = *sysrootCompile;
127 this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
130 if (cmValue sysrootLink =
131 this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
132 this->LinkerSysroot = *sysrootLink;
134 this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
137 if (cmValue appleArchSysroots =
138 this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
139 std::string const& appleArchs =
140 this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
141 std::vector<std::string> archs;
142 std::vector<std::string> sysroots;
143 cmExpandList(appleArchs, archs);
144 cmExpandList(*appleArchSysroots, sysroots, true);
145 if (archs.size() == sysroots.size()) {
146 for (size_t i = 0; i < archs.size(); ++i) {
147 this->AppleArchSysroots[archs[i]] = sysroots[i];
150 std::string const e =
151 cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n ", *appleArchSysroots,
153 "is not the same length as CMAKE_OSX_ARCHITECTURES:\n ",
155 this->IssueMessage(MessageType::FATAL_ERROR, e);
159 for (std::string const& lang : enabledLanguages) {
160 if (lang == "NONE") {
163 this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
165 this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
166 this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
168 std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
169 std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
170 std::string const& compilerOptionTarget =
171 "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
172 std::string const& compilerExternalToolchain =
173 "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
174 std::string const& compilerOptionExternalToolchain =
175 "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
176 std::string const& compilerOptionSysroot =
177 "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
179 this->VariableMappings[compilerArg1] =
180 this->Makefile->GetSafeDefinition(compilerArg1);
181 this->VariableMappings[compilerTarget] =
182 this->Makefile->GetSafeDefinition(compilerTarget);
183 this->VariableMappings[compilerOptionTarget] =
184 this->Makefile->GetSafeDefinition(compilerOptionTarget);
185 this->VariableMappings[compilerExternalToolchain] =
186 this->Makefile->GetSafeDefinition(compilerExternalToolchain);
187 this->VariableMappings[compilerOptionExternalToolchain] =
188 this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
189 this->VariableMappings[compilerOptionSysroot] =
190 this->Makefile->GetSafeDefinition(compilerOptionSysroot);
192 for (std::string replaceVar : ruleReplaceVars) {
193 if (replaceVar.find("${LANG}") != std::string::npos) {
194 cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
197 this->VariableMappings[replaceVar] =
198 this->Makefile->GetSafeDefinition(replaceVar);
203 cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
206 return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
207 this->CompilerSysroot,
208 this->LinkerSysroot);
211 cmLocalGenerator::~cmLocalGenerator() = default;
213 void cmLocalGenerator::IssueMessage(MessageType t,
214 std::string const& text) const
216 this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
219 void cmLocalGenerator::ComputeObjectMaxPath()
221 // Choose a maximum object file name length.
222 #if defined(_WIN32) || defined(__CYGWIN__)
223 this->ObjectPathMax = 250;
225 this->ObjectPathMax = 1000;
227 cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
228 if (cmNonempty(plen)) {
230 if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
232 this->ObjectPathMax = pmax;
234 std::ostringstream w;
235 w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
236 << ", which is less than the minimum of 128. "
237 << "The value will be ignored.";
238 this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
241 std::ostringstream w;
242 w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
243 << "\", which fails to parse as a positive integer. "
244 << "The value will be ignored.";
245 this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
248 this->ObjectMaxPathViolations.clear();
251 static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
252 const std::string& config,
253 const std::string& lang,
254 const cmGeneratorTarget* target)
261 includeDirs.begin(), includeDirs.end(),
262 [&target, &config, &lang](std::string const& a, std::string const& b) {
263 return !target->IsSystemIncludeDirectory(a, config, lang) &&
264 target->IsSystemIncludeDirectory(b, config, lang);
268 static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
269 const std::string& config,
270 const std::string& lang,
271 const cmGeneratorTarget* target)
277 std::stable_sort(includeDirs.begin(), includeDirs.end(),
278 [target, &config, &lang](BT<std::string> const& a,
279 BT<std::string> const& b) {
280 return !target->IsSystemIncludeDirectory(a.Value, config,
282 target->IsSystemIncludeDirectory(b.Value, config, lang);
286 void cmLocalGenerator::TraceDependencies() const
288 // Generate the rule files for each target.
289 const auto& targets = this->GetGeneratorTargets();
290 for (const auto& target : targets) {
291 if (!target->IsInBuildSystem()) {
294 target->TraceDependencies();
298 void cmLocalGenerator::GenerateTestFiles()
300 if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
304 // Compute the set of configurations.
305 std::vector<std::string> configurationTypes =
306 this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
307 std::string config = this->Makefile->GetDefaultConfiguration();
310 cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
311 "/CTestTestfile.cmake");
313 cmGeneratedFileStream fout(file);
314 fout.SetCopyIfDifferent(true);
316 fout << "# CMake generated Testfile for \n"
317 "# Source directory: "
318 << this->StateSnapshot.GetDirectory().GetCurrentSource()
320 "# Build directory: "
321 << this->StateSnapshot.GetDirectory().GetCurrentBinary()
324 "# This file includes the relevant testing commands "
326 "# testing this directory and lists subdirectories to "
327 "be tested as well.\n";
329 std::string resourceSpecFile =
330 this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
331 if (!resourceSpecFile.empty()) {
332 fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
335 cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
336 if (testIncludeFile) {
337 fout << "include(\"" << *testIncludeFile << "\")\n";
340 cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
341 if (testIncludeFiles) {
342 std::vector<std::string> includesList = cmExpandedList(*testIncludeFiles);
343 for (std::string const& i : includesList) {
344 fout << "include(\"" << i << "\")\n";
348 // Ask each test generator to write its code.
349 for (const auto& tester : this->Makefile->GetTestGenerators()) {
350 tester->Compute(this);
351 tester->Generate(fout, config, configurationTypes);
353 using vec_t = std::vector<cmStateSnapshot>;
354 vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
355 for (cmStateSnapshot const& i : children) {
356 // TODO: Use add_subdirectory instead?
357 std::string outP = i.GetDirectory().GetCurrentBinary();
358 outP = this->MaybeRelativeToCurBinDir(outP);
359 outP = cmOutputConverter::EscapeForCMake(outP);
360 fout << "subdirs(" << outP << ")\n";
363 // Add directory labels property
364 cmValue directoryLabels =
365 this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
366 cmValue labels = this->Makefile->GetProperty("LABELS");
368 if (labels || directoryLabels) {
369 fout << "set_directory_properties(PROPERTIES LABELS ";
371 fout << cmOutputConverter::EscapeForCMake(*labels);
373 if (labels && directoryLabels) {
376 if (directoryLabels) {
377 fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
383 void cmLocalGenerator::CreateEvaluationFileOutputs()
385 std::vector<std::string> const& configs =
386 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
387 for (std::string const& c : configs) {
388 this->CreateEvaluationFileOutputs(c);
392 void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
394 for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
395 geef->CreateOutputFile(this, config);
399 void cmLocalGenerator::ProcessEvaluationFiles(
400 std::vector<std::string>& generatedFiles)
402 for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
403 geef->Generate(this);
404 if (cmSystemTools::GetFatalErrorOccurred()) {
407 std::vector<std::string> files = geef->GetFiles();
408 std::sort(files.begin(), files.end());
410 std::vector<std::string> intersection;
411 std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
412 generatedFiles.end(),
413 std::back_inserter(intersection));
414 if (!intersection.empty()) {
415 cmSystemTools::Error("Files to be generated by multiple different "
417 cmWrap('"', intersection, '"', " "));
421 cm::append(generatedFiles, files);
422 std::inplace_merge(generatedFiles.begin(),
423 generatedFiles.end() - files.size(),
424 generatedFiles.end());
428 void cmLocalGenerator::GenerateInstallRules()
430 // Compute the install prefix.
431 cmValue installPrefix =
432 this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
433 std::string prefix = installPrefix;
435 #if defined(_WIN32) && !defined(__CYGWIN__)
436 if (!installPrefix) {
437 if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
440 cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
441 if (cmNonempty(project_name)) {
442 prefix += "/Program Files/";
443 prefix += *project_name;
445 prefix += "/InstalledCMakeProject";
448 #elif defined(__HAIKU__)
449 char dir[B_PATH_NAME_LENGTH];
450 if (!installPrefix) {
451 if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
455 prefix = "/boot/system";
459 if (!installPrefix) {
460 prefix = "/usr/local";
463 if (cmValue stagingPrefix =
464 this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
465 prefix = *stagingPrefix;
468 // Compute the set of configurations.
469 std::vector<std::string> configurationTypes =
470 this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
471 std::string config = this->Makefile->GetDefaultConfiguration();
473 // Choose a default install configuration.
474 std::string default_config = config;
475 const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
477 for (const char** c = default_order; *c && default_config.empty(); ++c) {
478 for (std::string const& configurationType : configurationTypes) {
479 if (cmSystemTools::UpperCase(configurationType) == *c) {
480 default_config = configurationType;
484 if (default_config.empty() && !configurationTypes.empty()) {
485 default_config = configurationTypes[0];
488 // Create the install script file.
489 std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
490 std::string homedir = this->GetState()->GetBinaryDirectory();
491 int toplevel_install = 0;
492 if (file == homedir) {
493 toplevel_install = 1;
495 file += "/cmake_install.cmake";
496 cmGeneratedFileStream fout(file);
497 fout.SetCopyIfDifferent(true);
500 /* clang-format off */
501 fout << "# Install script for directory: "
502 << this->StateSnapshot.GetDirectory().GetCurrentSource()
504 "# Set the install prefix\n"
505 "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
506 " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
508 << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
509 << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
510 /* clang-format on */
512 // Write support code for generating per-configuration install rules.
513 /* clang-format off */
515 "# Set the install configuration name.\n"
516 "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
518 " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
519 " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
521 " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
523 " message(STATUS \"Install configuration: "
524 "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
527 /* clang-format on */
529 // Write support code for dealing with component-specific installs.
530 /* clang-format off */
532 "# Set the component getting installed.\n"
533 "if(NOT CMAKE_INSTALL_COMPONENT)\n"
535 " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
536 " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
538 " set(CMAKE_INSTALL_COMPONENT)\n"
542 /* clang-format on */
544 // Copy user-specified install options to the install code.
545 if (cmValue so_no_exe =
546 this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
547 /* clang-format off */
549 "# Install shared libraries without execute permission?\n"
550 "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
551 " set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
554 /* clang-format on */
557 // Copy cmake cross compile state to install code.
558 if (cmValue crosscompiling =
559 this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
560 /* clang-format off */
562 "# Is this installation the result of a crosscompile?\n"
563 "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
564 " set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
567 /* clang-format on */
570 // Write default directory permissions.
571 if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
572 "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
573 /* clang-format off */
575 "# Set default install directory permissions.\n"
576 "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
577 " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
578 << *defaultDirPermissions << "\")\n"
581 /* clang-format on */
584 // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
585 // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
586 // has same platform variable as when running cmake
587 if (cmValue platform = this->Makefile->GetDefinition(
588 "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
589 /* clang-format off */
591 "# Set default install directory permissions.\n"
592 "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
593 " set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
594 << *platform << "\")\n"
597 /* clang-format on */
600 // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
601 // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
602 // has same tool selected as when running cmake
603 if (cmValue command =
604 this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
605 /* clang-format off */
607 "# Set default install directory permissions.\n"
608 "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
609 " set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
610 << *command << "\")\n"
613 /* clang-format on */
616 // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
617 // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
618 // has same path to the tool as when running cmake
619 if (cmValue command = this->Makefile->GetDefinition(
620 "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
621 /* clang-format off */
623 "# Set default install directory permissions.\n"
624 "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
625 " set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
626 << *command << "\")\n"
629 /* clang-format on */
632 // Write out CMAKE_OBJDUMP so that installed code that uses
633 // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
634 // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
635 // logic to fallback to CMAKE_OBJDUMP when `objdump` is
637 if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
638 /* clang-format off */
640 "# Set default install directory permissions.\n"
641 "if(NOT DEFINED CMAKE_OBJDUMP)\n"
642 " set(CMAKE_OBJDUMP \""
643 << *command << "\")\n"
646 /* clang-format on */
649 this->AddGeneratorSpecificInstallSetup(fout);
651 // Ask each install generator to write its code.
652 cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
653 auto const& installers = this->Makefile->GetInstallGenerators();
654 bool haveSubdirectoryInstall = false;
655 bool haveInstallAfterSubdirectory = false;
656 if (status == cmPolicies::WARN) {
657 for (const auto& installer : installers) {
658 installer->CheckCMP0082(haveSubdirectoryInstall,
659 haveInstallAfterSubdirectory);
660 installer->Generate(fout, config, configurationTypes);
663 for (const auto& installer : installers) {
664 installer->Generate(fout, config, configurationTypes);
668 // Write rules from old-style specification stored in targets.
669 this->GenerateTargetInstallRules(fout, config, configurationTypes);
671 // Include install scripts from subdirectories.
673 case cmPolicies::WARN:
674 if (haveInstallAfterSubdirectory &&
675 this->Makefile->PolicyOptionalWarningEnabled(
676 "CMAKE_POLICY_WARNING_CMP0082")) {
677 std::ostringstream e;
678 e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
679 this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
682 case cmPolicies::OLD: {
683 std::vector<cmStateSnapshot> children =
684 this->Makefile->GetStateSnapshot().GetChildren();
685 if (!children.empty()) {
686 fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
687 fout << " # Include the install script for each subdirectory.\n";
688 for (cmStateSnapshot const& c : children) {
689 if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
690 std::string odir = c.GetDirectory().GetCurrentBinary();
691 cmSystemTools::ConvertToUnixSlashes(odir);
692 fout << " include(\"" << odir << "/cmake_install.cmake\")\n";
696 fout << "endif()\n\n";
700 case cmPolicies::REQUIRED_IF_USED:
701 case cmPolicies::REQUIRED_ALWAYS:
702 case cmPolicies::NEW:
703 // NEW behavior is handled in
704 // cmInstallSubdirectoryGenerator::GenerateScript()
708 // Record the install manifest.
709 if (toplevel_install) {
710 /* clang-format off */
712 "if(CMAKE_INSTALL_COMPONENT)\n"
713 " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
714 "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
716 " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
719 "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
720 " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
721 "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
722 " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
723 /* clang-format on */
727 void cmLocalGenerator::AddGeneratorTarget(
728 std::unique_ptr<cmGeneratorTarget> gt)
730 cmGeneratorTarget* gt_ptr = gt.get();
732 this->GeneratorTargets.push_back(std::move(gt));
733 this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
734 this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
737 void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
739 this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
740 this->GlobalGenerator->IndexGeneratorTarget(gt);
743 void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
744 std::unique_ptr<cmGeneratorTarget> gt)
746 this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
749 cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
750 const std::string& name) const
752 auto ti = this->GeneratorTargetSearchIndex.find(name);
753 if (ti != this->GeneratorTargetSearchIndex.end()) {
759 void cmLocalGenerator::ComputeTargetManifest()
761 // Collect the set of configuration types.
762 std::vector<std::string> configNames =
763 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
765 // Add our targets to the manifest for each configuration.
766 const auto& targets = this->GetGeneratorTargets();
767 for (const auto& target : targets) {
768 if (!target->IsInBuildSystem()) {
771 for (std::string const& c : configNames) {
772 target->ComputeTargetManifest(c);
777 bool cmLocalGenerator::ComputeTargetCompileFeatures()
779 // Collect the set of configuration types.
780 std::vector<std::string> configNames =
781 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
783 using LanguagePair = std::pair<std::string, std::string>;
784 std::vector<LanguagePair> pairedLanguages{
785 { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
787 std::set<LanguagePair> inferredEnabledLanguages;
788 for (auto const& lang : pairedLanguages) {
789 if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
790 inferredEnabledLanguages.insert(lang);
794 // Process compile features of all targets.
795 const auto& targets = this->GetGeneratorTargets();
796 for (const auto& target : targets) {
797 for (std::string const& c : configNames) {
798 if (!target->ComputeCompileFeatures(c)) {
803 // Now that C/C++ _STANDARD values have been computed
804 // set the values to ObjC/ObjCXX _STANDARD variables
805 if (target->CanCompileSources()) {
806 for (std::string const& c : configNames) {
807 target->ComputeCompileFeatures(c, inferredEnabledLanguages);
815 bool cmLocalGenerator::IsRootMakefile() const
817 return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
820 cmState* cmLocalGenerator::GetState() const
822 return this->GlobalGenerator->GetCMakeInstance()->GetState();
825 cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
827 return this->Makefile->GetStateSnapshot();
830 cmValue cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
831 const std::string& prop)
834 return target->GetProperty(prop);
836 return this->Makefile->GetProperty(prop);
839 std::string cmLocalGenerator::ConvertToIncludeReference(
840 std::string const& path, OutputFormat format)
842 return this->ConvertToOutputForExisting(path, format);
845 std::string cmLocalGenerator::GetIncludeFlags(
846 std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
847 std::string const& lang, std::string const& config, bool forResponseFile)
853 std::vector<std::string> includes = includeDirs;
854 MoveSystemIncludesToEnd(includes, config, lang, target);
856 OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
857 std::ostringstream includeFlags;
859 std::string const& includeFlag =
860 this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
861 bool quotePaths = false;
862 if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
865 std::string sep = " ";
866 bool repeatFlag = true;
867 // should the include flag be repeated like ie. -IA -IB
868 if (cmValue incSep = this->Makefile->GetDefinition(
869 cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
870 // if there is a separator then the flag is not repeated but is only
871 // given once i.e. -classpath a:b:c
876 // Support special system include flag if it is available and the
877 // normal flag is repeated for each directory.
878 cmValue sysIncludeFlag = nullptr;
879 cmValue sysIncludeFlagWarning = nullptr;
881 sysIncludeFlag = this->Makefile->GetDefinition(
882 cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
883 sysIncludeFlagWarning = this->Makefile->GetDefinition(
884 cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
887 cmValue fwSearchFlag = this->Makefile->GetDefinition(
888 cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
889 cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
890 cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
892 bool flagUsed = false;
893 bool sysIncludeFlagUsed = false;
894 std::set<std::string> emitted;
896 emitted.insert("/System/Library/Frameworks");
898 for (std::string const& i : includes) {
899 if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
900 cmSystemTools::IsPathToFramework(i)) {
901 std::string const frameworkDir =
902 cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
903 if (emitted.insert(frameworkDir).second) {
904 if (sysFwSearchFlag && target &&
905 target->IsSystemIncludeDirectory(i, config, lang)) {
906 includeFlags << *sysFwSearchFlag;
908 includeFlags << *fwSearchFlag;
910 includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
916 if (!flagUsed || repeatFlag) {
917 if (sysIncludeFlag && target &&
918 target->IsSystemIncludeDirectory(i, config, lang)) {
919 includeFlags << *sysIncludeFlag;
920 sysIncludeFlagUsed = true;
922 includeFlags << includeFlag;
926 std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
927 if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
928 includeFlags << "\"";
930 includeFlags << includePath;
931 if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
932 includeFlags << "\"";
936 if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
937 includeFlags << *sysIncludeFlagWarning;
939 std::string flags = includeFlags.str();
940 // remove trailing separators
941 if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
944 return cmTrimWhitespace(flags);
947 void cmLocalGenerator::AddCompileOptions(std::string& flags,
948 cmGeneratorTarget* target,
949 const std::string& lang,
950 const std::string& config)
952 std::vector<BT<std::string>> tmpFlags;
953 this->AddCompileOptions(tmpFlags, target, lang, config);
954 this->AppendFlags(flags, tmpFlags);
957 void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
958 cmGeneratorTarget* target,
959 const std::string& lang,
960 const std::string& config)
962 std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
964 if (cmValue langFlagRegexStr =
965 this->Makefile->GetDefinition(langFlagRegexVar)) {
966 // Filter flags acceptable to this language.
967 if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
968 std::vector<std::string> opts;
969 cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
970 // Re-escape these flags since COMPILE_FLAGS were already parsed
971 // as a command line above.
972 std::string compileOpts;
973 this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
974 if (!compileOpts.empty()) {
975 flags.emplace_back(std::move(compileOpts));
978 std::vector<BT<std::string>> targetCompileOpts =
979 target->GetCompileOptions(config, lang);
980 // COMPILE_OPTIONS are escaped.
981 this->AppendCompileOptions(flags, targetCompileOpts,
982 langFlagRegexStr->c_str());
985 if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
986 // COMPILE_FLAGS are not escaped for historical reasons.
987 std::string compileFlags;
988 this->AppendFlags(compileFlags, *targetFlags);
989 if (!compileFlags.empty()) {
990 flags.emplace_back(std::move(compileFlags));
993 std::vector<BT<std::string>> targetCompileOpts =
994 target->GetCompileOptions(config, lang);
995 // COMPILE_OPTIONS are escaped.
996 this->AppendCompileOptions(flags, targetCompileOpts);
999 cmStandardLevelResolver standardResolver(this->Makefile);
1000 for (auto const& it : target->GetMaxLanguageStandards()) {
1001 cmValue standard = target->GetLanguageStandard(it.first, config);
1005 if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
1006 std::ostringstream e;
1007 e << "The COMPILE_FEATURES property of target \"" << target->GetName()
1008 << "\" was evaluated when computing the link "
1009 "implementation, and the \""
1010 << it.first << "_STANDARD\" was \"" << it.second
1011 << "\" for that computation. Computing the "
1012 "COMPILE_FEATURES based on the link implementation resulted in a "
1014 << it.first << "_STANDARD\" \"" << *standard
1016 "This is not permitted. The COMPILE_FEATURES may not both depend "
1018 "and be depended on by the link implementation.\n";
1019 this->IssueMessage(MessageType::FATAL_ERROR, e.str());
1024 std::string compReqFlag;
1025 this->AddCompilerRequirementFlag(compReqFlag, target, lang, config);
1026 if (!compReqFlag.empty()) {
1027 flags.emplace_back(std::move(compReqFlag));
1030 // Add Warning as errors flags
1031 if (!this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
1032 const cmValue wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
1033 const cmValue wErrorOpts = this->Makefile->GetDefinition(
1034 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
1035 if (wError.IsOn() && wErrorOpts.IsSet()) {
1036 std::string wErrorFlags;
1037 this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
1038 if (!wErrorFlags.empty()) {
1039 flags.emplace_back(std::move(wErrorFlags));
1044 // Add compile flag for the MSVC compiler only.
1045 cmMakefile* mf = this->GetMakefile();
1047 mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
1049 // Handle Just My Code debugging flags, /JMC.
1050 // If the target is a Managed C++ one, /JMC is not compatible.
1051 if (target->GetManagedType(config) !=
1052 cmGeneratorTarget::ManagedType::Managed) {
1053 // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
1055 if (cmValue jmcExprGen =
1056 target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
1057 std::string isJMCEnabled =
1058 cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
1059 if (cmIsOn(isJMCEnabled)) {
1060 std::vector<std::string> optVec = cmExpandedList(*jmc);
1061 std::string jmcFlags;
1062 this->AppendCompileOptions(jmcFlags, optVec);
1063 if (!jmcFlags.empty()) {
1064 flags.emplace_back(std::move(jmcFlags));
1072 cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
1073 const std::string& target, cmCustomCommandType type,
1074 std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
1076 cmTarget* t = this->Makefile->GetCustomCommandTarget(
1077 target, objLibCommands, this->DirectoryBacktrace);
1082 cc->SetBacktrace(this->DirectoryBacktrace);
1084 detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
1090 cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
1091 std::unique_ptr<cmCustomCommand> cc, bool replace)
1093 // Make sure there is at least one output.
1094 if (cc->GetOutputs().empty()) {
1095 cmSystemTools::Error("Attempt to add a custom rule with no output!");
1099 cc->SetBacktrace(this->DirectoryBacktrace);
1100 return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
1101 std::move(cc), replace);
1104 cmTarget* cmLocalGenerator::AddUtilityCommand(
1105 const std::string& utilityName, bool excludeFromAll,
1106 std::unique_ptr<cmCustomCommand> cc)
1109 this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
1110 target->SetIsGeneratorProvided(true);
1112 if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
1116 cc->SetBacktrace(this->DirectoryBacktrace);
1117 detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
1123 std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
1124 cmGeneratorTarget const* target, std::string const& lang,
1125 std::string const& config, bool stripImplicitDirs,
1126 bool appendAllImplicitDirs) const
1128 std::vector<BT<std::string>> result;
1129 // Do not repeat an include path.
1130 std::set<std::string> emitted;
1132 auto emitDir = [&result, &emitted](std::string const& dir) {
1133 if (emitted.insert(dir).second) {
1134 result.emplace_back(dir);
1138 auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
1139 if (emitted.insert(dir.Value).second) {
1140 result.emplace_back(dir);
1144 // When automatic include directories are requested for a build then
1145 // include the source and binary directories at the beginning of the
1146 // include path to approximate include file behavior for an
1147 // in-source build. This does not account for the case of a source
1148 // file in a subdirectory of the current source directory but we
1149 // cannot fix this because not all native build tools support
1150 // per-source-file include paths.
1151 if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
1152 // Current binary directory
1153 emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
1154 // Current source directory
1155 emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
1162 // Standard include directories to be added unconditionally at the end.
1163 // These are intended to simulate additional implicit include directories.
1164 std::vector<std::string> userStandardDirs;
1166 std::string const value = this->Makefile->GetSafeDefinition(
1167 cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
1168 cmExpandList(value, userStandardDirs);
1169 for (std::string& usd : userStandardDirs) {
1170 cmSystemTools::ConvertToUnixSlashes(usd);
1174 // Implicit include directories
1175 std::vector<std::string> implicitDirs;
1176 std::set<std::string> implicitSet;
1177 // Include directories to be excluded as if they were implicit.
1178 std::set<std::string> implicitExclude;
1180 // Raw list of implicit include directories
1181 // Start with "standard" directories that we unconditionally add below.
1182 std::vector<std::string> impDirVec = userStandardDirs;
1184 // Load implicit include directories for this language.
1185 // We ignore this for Fortran because:
1186 // * There are no standard library headers to avoid overriding.
1187 // * Compilers like gfortran do not search their own implicit include
1188 // directories for modules ('.mod' files).
1189 if (lang != "Fortran") {
1190 size_t const impDirVecOldSize = impDirVec.size();
1191 if (this->Makefile->GetDefExpandList(
1192 cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES"),
1194 // FIXME: Use cmRange with 'advance()' when it supports non-const.
1195 for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
1196 cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
1201 // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
1202 // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
1203 // variables are now computed. On macOS the /usr/include directory is
1204 // inside the platform SDK so the computed value does not contain it
1205 // directly. In this case adding -I/usr/include can hide SDK headers so we
1206 // must still exclude it.
1207 if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
1208 !cm::contains(impDirVec, "/usr/include") &&
1209 std::find_if(impDirVec.begin(), impDirVec.end(),
1210 [](std::string const& d) {
1211 return cmHasLiteralSuffix(d, "/usr/include");
1212 }) != impDirVec.end()) {
1213 // Only exclude this hard coded path for backwards compatibility.
1214 implicitExclude.emplace("/usr/include");
1217 for (std::string const& i : impDirVec) {
1218 if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
1219 implicitDirs.emplace_back(i);
1224 bool const isCorCxx = (lang == "C" || lang == "CXX");
1226 // Resolve symlinks in CPATH for comparison with resolved include paths.
1227 // We do this here instead of when EnvCPATH is populated in case symlinks
1228 // on disk have changed in the meantime.
1229 std::set<std::string> resolvedEnvCPATH;
1231 for (std::string const& i : this->EnvCPATH) {
1232 resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
1236 // Checks if this is not an excluded (implicit) include directory.
1237 auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
1238 isCorCxx](std::string const& dir) -> bool {
1239 std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
1241 // Do not exclude directories that are not in any excluded set.
1242 !(cm::contains(implicitSet, real_dir) ||
1243 cm::contains(implicitExclude, dir))
1244 // Do not exclude entries of the CPATH environment variable even though
1245 // they are implicitly searched by the compiler. They are meant to be
1246 // user-specified directories that can be re-ordered or converted to
1247 // -isystem without breaking real compiler builtin headers.
1248 || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
1251 // Get the target-specific include directories.
1252 std::vector<BT<std::string>> userDirs =
1253 target->GetIncludeDirectories(config, lang);
1255 // Support putting all the in-project include directories first if
1256 // it is requested by the project.
1257 if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
1258 std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
1259 std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
1260 for (BT<std::string> const& udr : userDirs) {
1261 // Emit this directory only if it is a subdirectory of the
1262 // top-level source or binary tree.
1263 if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
1264 cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
1265 cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
1266 cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
1267 if (notExcluded(udr.Value)) {
1274 // Emit remaining non implicit user directories.
1275 for (BT<std::string> const& udr : userDirs) {
1276 if (notExcluded(udr.Value)) {
1282 MoveSystemIncludesToEnd(result, config, lang, target);
1284 // Append standard include directories for this language.
1285 userDirs.reserve(userDirs.size() + userStandardDirs.size());
1286 for (std::string& usd : userStandardDirs) {
1288 userDirs.emplace_back(std::move(usd));
1291 // Append compiler implicit include directories
1292 if (!stripImplicitDirs) {
1293 // Append implicit directories that were requested by the user only
1294 for (BT<std::string> const& udr : userDirs) {
1295 if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
1299 // Append remaining implicit directories (on demand)
1300 if (appendAllImplicitDirs) {
1301 for (std::string& imd : implicitDirs) {
1310 void cmLocalGenerator::GetIncludeDirectoriesImplicit(
1311 std::vector<std::string>& dirs, cmGeneratorTarget const* target,
1312 const std::string& lang, const std::string& config, bool stripImplicitDirs,
1313 bool appendAllImplicitDirs) const
1315 std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
1316 target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
1317 dirs.reserve(dirs.size() + tmp.size());
1318 for (BT<std::string>& v : tmp) {
1319 dirs.emplace_back(std::move(v.Value));
1323 std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
1324 cmGeneratorTarget const* target, std::string const& lang,
1325 std::string const& config) const
1327 return this->GetIncludeDirectoriesImplicit(target, lang, config);
1330 void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
1331 cmGeneratorTarget const* target,
1332 const std::string& lang,
1333 const std::string& config) const
1335 this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
1338 void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
1339 std::string const& config,
1340 std::string const& linkLanguage,
1341 cmGeneratorTarget* target)
1343 std::vector<BT<std::string>> tmpFlags =
1344 this->GetStaticLibraryFlags(config, linkLanguage, target);
1345 this->AppendFlags(flags, tmpFlags);
1348 std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
1349 std::string const& config, std::string const& linkLanguage,
1350 cmGeneratorTarget* target)
1352 const std::string configUpper = cmSystemTools::UpperCase(config);
1353 std::vector<BT<std::string>> flags;
1354 if (linkLanguage != "Swift") {
1355 std::string staticLibFlags;
1358 this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
1359 if (!configUpper.empty()) {
1360 std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
1361 this->AppendFlags(staticLibFlags,
1362 this->Makefile->GetSafeDefinition(name));
1364 if (!staticLibFlags.empty()) {
1365 flags.emplace_back(std::move(staticLibFlags));
1369 std::string staticLibFlags;
1370 this->AppendFlags(staticLibFlags,
1371 target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
1372 if (!configUpper.empty()) {
1373 std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
1374 this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
1377 if (!staticLibFlags.empty()) {
1378 flags.emplace_back(std::move(staticLibFlags));
1381 std::vector<BT<std::string>> staticLibOpts =
1382 target->GetStaticLibraryLinkOptions(config, linkLanguage);
1383 // STATIC_LIBRARY_OPTIONS are escaped.
1384 this->AppendCompileOptions(flags, staticLibOpts);
1389 void cmLocalGenerator::GetDeviceLinkFlags(
1390 cmLinkLineDeviceComputer& linkLineComputer, const std::string& config,
1391 std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
1392 std::string& linkPath, cmGeneratorTarget* target)
1394 cmGeneratorTarget::DeviceLinkSetter setter(*target);
1396 cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
1398 auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
1399 auto ipoEnabled = target->IsIPOEnabled(linklang, config);
1401 ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
1404 if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
1405 "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
1406 linkFlags += cudaIPOFlags;
1411 // Compute the required device link libraries when
1412 // resolving gpu lang device symbols
1413 this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
1417 // iterate link deps and see if any of them need IPO
1419 std::vector<std::string> linkOpts;
1420 target->GetLinkOptions(linkOpts, config, "CUDA");
1421 // LINK_OPTIONS are escaped.
1422 this->AppendCompileOptions(linkFlags, linkOpts);
1425 void cmLocalGenerator::GetTargetFlags(
1426 cmLinkLineComputer* linkLineComputer, const std::string& config,
1427 std::string& linkLibs, std::string& flags, std::string& linkFlags,
1428 std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
1430 std::vector<BT<std::string>> linkFlagsList;
1431 std::vector<BT<std::string>> linkPathList;
1432 std::vector<BT<std::string>> linkLibsList;
1433 this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
1434 linkFlagsList, frameworkPath, linkPathList, target);
1435 this->AppendFlags(linkFlags, linkFlagsList);
1436 this->AppendFlags(linkPath, linkPathList);
1437 this->AppendFlags(linkLibs, linkLibsList);
1440 void cmLocalGenerator::GetTargetFlags(
1441 cmLinkLineComputer* linkLineComputer, const std::string& config,
1442 std::vector<BT<std::string>>& linkLibs, std::string& flags,
1443 std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
1444 std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
1446 const std::string configUpper = cmSystemTools::UpperCase(config);
1447 cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
1448 const char* libraryLinkVariable =
1449 "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
1451 const std::string linkLanguage =
1452 linkLineComputer->GetLinkerLanguage(target, config);
1454 switch (target->GetType()) {
1455 case cmStateEnums::STATIC_LIBRARY:
1456 linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
1458 case cmStateEnums::MODULE_LIBRARY:
1459 libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
1461 case cmStateEnums::SHARED_LIBRARY: {
1462 std::string sharedLibFlags;
1463 if (linkLanguage != "Swift") {
1464 sharedLibFlags = cmStrCat(
1465 this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
1466 if (!configUpper.empty()) {
1467 std::string build = cmStrCat(libraryLinkVariable, '_', configUpper);
1468 sharedLibFlags += this->Makefile->GetSafeDefinition(build);
1469 sharedLibFlags += " ";
1473 cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
1474 if (targetLinkFlags) {
1475 sharedLibFlags += *targetLinkFlags;
1476 sharedLibFlags += " ";
1478 if (!configUpper.empty()) {
1480 target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
1481 if (targetLinkFlags) {
1482 sharedLibFlags += *targetLinkFlags;
1483 sharedLibFlags += " ";
1487 if (!sharedLibFlags.empty()) {
1488 linkFlags.emplace_back(std::move(sharedLibFlags));
1491 std::vector<BT<std::string>> linkOpts =
1492 target->GetLinkOptions(config, linkLanguage);
1493 // LINK_OPTIONS are escaped.
1494 this->AppendCompileOptions(linkFlags, linkOpts);
1496 this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
1497 frameworkPath, linkPath);
1500 case cmStateEnums::EXECUTABLE: {
1501 std::string exeFlags;
1502 if (linkLanguage != "Swift") {
1503 exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
1505 if (!configUpper.empty()) {
1506 exeFlags += this->Makefile->GetSafeDefinition(
1507 cmStrCat("CMAKE_EXE_LINKER_FLAGS_", configUpper));
1510 if (linkLanguage.empty()) {
1511 cmSystemTools::Error(
1512 "CMake can not determine linker language for target: " +
1517 if (target->IsWin32Executable(config)) {
1518 exeFlags += this->Makefile->GetSafeDefinition(
1519 cmStrCat("CMAKE_", linkLanguage, "_CREATE_WIN32_EXE"));
1522 exeFlags += this->Makefile->GetSafeDefinition(
1523 cmStrCat("CMAKE_", linkLanguage, "_CREATE_CONSOLE_EXE"));
1527 if (target->IsExecutableWithExports()) {
1528 exeFlags += this->Makefile->GetSafeDefinition(
1529 cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
1534 this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
1536 this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
1537 frameworkPath, linkPath);
1540 if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
1541 std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
1542 exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
1546 std::string cmp0065Flags =
1547 this->GetLinkLibsCMP0065(linkLanguage, *target);
1548 if (!cmp0065Flags.empty()) {
1549 exeFlags += cmp0065Flags;
1553 cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
1554 if (targetLinkFlags) {
1555 exeFlags += *targetLinkFlags;
1558 if (!configUpper.empty()) {
1560 target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
1561 if (targetLinkFlags) {
1562 exeFlags += *targetLinkFlags;
1567 if (!exeFlags.empty()) {
1568 linkFlags.emplace_back(std::move(exeFlags));
1571 std::vector<BT<std::string>> linkOpts =
1572 target->GetLinkOptions(config, linkLanguage);
1573 // LINK_OPTIONS are escaped.
1574 this->AppendCompileOptions(linkFlags, linkOpts);
1580 std::string extraLinkFlags;
1581 this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
1583 this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
1584 this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
1587 if (!extraLinkFlags.empty()) {
1588 linkFlags.emplace_back(std::move(extraLinkFlags));
1592 void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
1593 std::string const& config,
1594 std::string const& lang,
1596 std::string const& arch)
1598 std::vector<BT<std::string>> tmpFlags =
1599 this->GetTargetCompileFlags(target, config, lang, arch);
1600 this->AppendFlags(flags, tmpFlags);
1603 std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
1604 cmGeneratorTarget* target, std::string const& config,
1605 std::string const& lang, std::string const& arch)
1607 std::vector<BT<std::string>> flags;
1608 std::string compileFlags;
1610 cmMakefile* mf = this->GetMakefile();
1612 // Add language-specific flags.
1613 this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
1616 if (target->IsIPOEnabled(lang, config)) {
1617 this->AppendFeatureOptions(compileFlags, lang, "IPO");
1620 this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
1622 if (lang == "Fortran") {
1623 this->AppendFlags(compileFlags,
1624 this->GetTargetFortranFlags(target, config));
1627 this->AddCMP0018Flags(compileFlags, target, lang, config);
1628 this->AddVisibilityPresetFlags(compileFlags, target, lang);
1629 this->AddColorDiagnosticsFlags(compileFlags, lang);
1630 this->AppendFlags(compileFlags, mf->GetDefineFlags());
1631 this->AppendFlags(compileFlags,
1632 this->GetFrameworkFlags(lang, config, target));
1634 if (!compileFlags.empty()) {
1635 flags.emplace_back(std::move(compileFlags));
1637 this->AddCompileOptions(flags, target, lang, config);
1641 static std::string GetFrameworkFlags(const std::string& lang,
1642 const std::string& config,
1643 cmGeneratorTarget* target)
1645 cmLocalGenerator* lg = target->GetLocalGenerator();
1646 cmMakefile* mf = lg->GetMakefile();
1648 if (!mf->IsOn("APPLE")) {
1649 return std::string();
1652 std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
1653 cmValue fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
1654 if (!cmNonempty(fwSearchFlag)) {
1655 return std::string();
1658 std::set<std::string> emitted;
1659 #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
1660 emitted.insert("/System/Library/Frameworks");
1662 std::vector<std::string> includes;
1664 lg->GetIncludeDirectories(includes, target, "C", config);
1665 // check all include directories for frameworks as this
1666 // will already have added a -F for the framework
1667 for (std::string const& include : includes) {
1668 if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
1669 std::string frameworkDir = cmStrCat(include, "/../");
1670 frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
1671 emitted.insert(frameworkDir);
1676 if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
1677 std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
1678 for (std::string const& framework : frameworks) {
1679 if (emitted.insert(framework).second) {
1680 flags += *fwSearchFlag;
1682 lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
1690 std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
1691 std::string const& config,
1692 cmGeneratorTarget* target)
1694 return ::GetFrameworkFlags(l, config, target);
1697 void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
1698 std::string const& config,
1699 std::string const& lang,
1700 std::set<std::string>& defines) const
1702 std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
1703 for (BT<std::string> const& v : tmp) {
1704 defines.emplace(v.Value);
1708 std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
1709 cmGeneratorTarget const* target, std::string const& config,
1710 std::string const& lang) const
1712 std::set<BT<std::string>> defines;
1714 // Add the export symbol definition for shared library objects.
1715 if (const std::string* exportMacro = target->GetExportMacro()) {
1716 this->AppendDefines(defines, *exportMacro);
1719 // Add preprocessor definitions for this target and configuration.
1720 std::vector<BT<std::string>> targetDefines =
1721 target->GetCompileDefinitions(config, lang);
1722 this->AppendDefines(defines, targetDefines);
1727 std::string cmLocalGenerator::GetTargetFortranFlags(
1728 cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
1730 // Implemented by specific generators that override this.
1731 return std::string();
1735 * Output the linking rules on a command line. For executables,
1736 * targetLibrary should be a NULL pointer. For libraries, it should point
1737 * to the name of the library. This will not link a library against itself.
1739 void cmLocalGenerator::OutputLinkLibraries(
1740 cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
1741 std::string& linkLibraries, std::string& frameworkPath,
1742 std::string& linkPath)
1744 std::vector<BT<std::string>> linkLibrariesList;
1745 std::vector<BT<std::string>> linkPathList;
1746 this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
1747 frameworkPath, linkPathList);
1748 pcli->AppendValues(linkLibraries, linkLibrariesList);
1749 pcli->AppendValues(linkPath, linkPathList);
1752 void cmLocalGenerator::OutputLinkLibraries(
1753 cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
1754 std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
1755 std::vector<BT<std::string>>& linkPath)
1757 cmComputeLinkInformation& cli = *pcli;
1759 std::string linkLanguage = cli.GetLinkLanguage();
1761 std::string libPathFlag;
1762 if (cmValue value = this->Makefile->GetDefinition(
1763 "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
1764 libPathFlag = *value;
1767 this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
1770 std::string libPathTerminator;
1771 if (cmValue value = this->Makefile->GetDefinition(
1772 "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
1773 libPathTerminator = *value;
1776 this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
1779 // Add standard libraries for this language.
1780 std::string stdLibString = this->Makefile->GetSafeDefinition(
1781 cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
1783 // Append the framework search path flags.
1784 std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
1785 cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
1787 frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
1788 linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
1790 linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
1793 std::string cmLocalGenerator::GetLinkLibsCMP0065(
1794 std::string const& linkLanguage, cmGeneratorTarget& tgt) const
1796 std::string linkFlags;
1798 // Flags to link an executable to shared libraries.
1799 if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
1800 this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
1801 "TARGET_SUPPORTS_SHARED_LIBS")) {
1802 bool add_shlib_flags = false;
1803 switch (tgt.GetPolicyStatusCMP0065()) {
1804 case cmPolicies::WARN:
1805 if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
1806 this->Makefile->PolicyOptionalWarningEnabled(
1807 "CMAKE_POLICY_WARNING_CMP0065")) {
1808 std::ostringstream w;
1809 /* clang-format off */
1810 w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
1811 "For compatibility with older versions of CMake, "
1812 "additional flags may be added to export symbols on all "
1813 "executables regardless of their ENABLE_EXPORTS property.";
1814 /* clang-format on */
1815 this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
1818 case cmPolicies::OLD:
1819 // OLD behavior is to always add the flags, except on AIX where
1820 // we compute symbol exports if ENABLE_EXPORTS is on.
1822 !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
1824 case cmPolicies::REQUIRED_IF_USED:
1825 case cmPolicies::REQUIRED_ALWAYS:
1827 MessageType::FATAL_ERROR,
1828 cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
1830 case cmPolicies::NEW:
1831 // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
1832 // except on AIX where we compute symbol exports.
1834 !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
1838 if (add_shlib_flags) {
1839 linkFlags = this->Makefile->GetSafeDefinition(
1840 cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
1846 bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
1847 const std::vector<std::string>& archs, cmValue sysroot)
1853 return std::all_of(archs.begin(), archs.end(),
1854 [this, sysroot](std::string const& arch) -> bool {
1855 std::string const& archSysroot =
1856 this->AppleArchSysroots[arch];
1857 return cmIsOff(archSysroot) || sysroot == archSysroot;
1861 void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
1862 cmGeneratorTarget const* target,
1863 const std::string& lang,
1864 const std::string& config,
1865 const std::string& filterArch)
1867 // Only add Apple specific flags on Apple platforms
1868 if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
1869 std::vector<std::string> archs;
1870 target->GetAppleArchs(config, archs);
1871 if (!archs.empty() &&
1872 (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
1874 for (std::string const& arch : archs) {
1875 if (filterArch.empty() || filterArch == arch) {
1882 cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
1883 if (sysroot && *sysroot == "/") {
1886 std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
1887 cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
1888 if (cmNonempty(sysrootFlag)) {
1889 if (!this->AppleArchSysroots.empty() &&
1890 !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
1891 for (std::string const& arch : archs) {
1892 std::string const& archSysroot = this->AppleArchSysroots[arch];
1893 if (cmIsOff(archSysroot)) {
1896 if (filterArch.empty() || filterArch == arch) {
1897 flags += " -Xarch_" + arch + " ";
1898 // Combine sysroot flag and path to work with -Xarch
1899 std::string arch_sysroot = *sysrootFlag + archSysroot;
1900 flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
1903 } else if (cmNonempty(sysroot)) {
1905 flags += *sysrootFlag;
1907 flags += this->ConvertToOutputFormat(*sysroot, SHELL);
1911 cmValue deploymentTarget =
1912 this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
1913 std::string deploymentTargetFlagVar =
1914 "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
1915 cmValue deploymentTargetFlag =
1916 this->Makefile->GetDefinition(deploymentTargetFlagVar);
1917 if (cmNonempty(deploymentTargetFlag) && cmNonempty(deploymentTarget)) {
1919 flags += *deploymentTargetFlag;
1920 flags += *deploymentTarget;
1925 void cmLocalGenerator::AddLanguageFlags(std::string& flags,
1926 cmGeneratorTarget const* target,
1927 cmBuildStep compileOrLink,
1928 const std::string& lang,
1929 const std::string& config)
1931 // Add language-specific flags.
1932 this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
1935 std::string compiler = this->Makefile->GetSafeDefinition(
1936 cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
1938 std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
1939 cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
1941 if (lang == "Swift") {
1942 if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
1943 if (cmSystemTools::VersionCompare(
1944 cmSystemTools::OP_GREATER_EQUAL,
1945 this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
1947 this->AppendFlags(flags, "-swift-version " + *v);
1950 } else if (lang == "CUDA") {
1951 target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
1952 target->AddCUDAToolkitFlags(flags);
1953 } else if (lang == "ISPC") {
1954 target->AddISPCTargetFlags(flags);
1955 } else if (lang == "RC" &&
1956 this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
1957 .find("llvm-rc") != std::string::npos) {
1958 compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
1959 if (!compiler.empty()) {
1960 compilerSimulateId =
1961 this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
1963 compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
1964 compilerSimulateId =
1965 this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
1967 } else if (lang == "HIP") {
1968 target->AddHIPArchitectureFlags(flags);
1971 // Add VFS Overlay for Clang compilers
1972 if (compiler == "Clang") {
1973 if (cmValue vfsOverlay =
1974 this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
1975 if (compilerSimulateId == "MSVC") {
1976 this->AppendCompileOptions(
1978 std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
1981 this->AppendCompileOptions(
1982 flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
1986 // Add MSVC runtime library flags. This is activated by the presence
1987 // of a default selection whether or not it is overridden by a property.
1988 cmValue msvcRuntimeLibraryDefault =
1989 this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
1990 if (cmNonempty(msvcRuntimeLibraryDefault)) {
1991 cmValue msvcRuntimeLibraryValue =
1992 target->GetProperty("MSVC_RUNTIME_LIBRARY");
1993 if (!msvcRuntimeLibraryValue) {
1994 msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
1996 std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
1997 *msvcRuntimeLibraryValue, this, config, target);
1998 if (!msvcRuntimeLibrary.empty()) {
1999 if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
2000 "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
2001 msvcRuntimeLibrary)) {
2002 this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
2003 } else if ((this->Makefile->GetSafeDefinition(
2004 "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
2005 this->Makefile->GetSafeDefinition(
2006 "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
2007 !cmSystemTools::GetErrorOccurredFlag()) {
2008 // The compiler uses the MSVC ABI so it needs a known runtime library.
2009 this->IssueMessage(MessageType::FATAL_ERROR,
2010 "MSVC_RUNTIME_LIBRARY value '" +
2011 msvcRuntimeLibrary + "' not known for this " +
2012 lang + " compiler.");
2017 // Add Watcom runtime library flags. This is activated by the presence
2018 // of a default selection whether or not it is overridden by a property.
2019 cmValue watcomRuntimeLibraryDefault =
2020 this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
2021 if (cmNonempty(watcomRuntimeLibraryDefault)) {
2022 cmValue watcomRuntimeLibraryValue =
2023 target->GetProperty("WATCOM_RUNTIME_LIBRARY");
2024 if (!watcomRuntimeLibraryValue) {
2025 watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
2027 std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
2028 *watcomRuntimeLibraryValue, this, config, target);
2029 if (!watcomRuntimeLibrary.empty()) {
2030 if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
2031 "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
2032 watcomRuntimeLibrary)) {
2033 this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
2034 } else if ((this->Makefile->GetSafeDefinition(
2035 "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
2036 this->Makefile->GetSafeDefinition(
2037 "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
2038 !cmSystemTools::GetErrorOccurredFlag()) {
2039 // The compiler uses the Watcom ABI so it needs a known runtime
2041 this->IssueMessage(MessageType::FATAL_ERROR,
2042 "WATCOM_RUNTIME_LIBRARY value '" +
2043 watcomRuntimeLibrary + "' not known for this " +
2044 lang + " compiler.");
2049 // Add MSVC debug information format flags if CMP0141 is NEW.
2050 if (cm::optional<std::string> msvcDebugInformationFormat =
2051 this->GetMSVCDebugFormatName(config, target)) {
2052 if (!msvcDebugInformationFormat->empty()) {
2053 if (cmValue msvcDebugInformationFormatOptions =
2054 this->Makefile->GetDefinition(
2055 cmStrCat("CMAKE_", lang,
2056 "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
2057 *msvcDebugInformationFormat))) {
2058 this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
2059 } else if ((this->Makefile->GetSafeDefinition(
2060 cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
2061 this->Makefile->GetSafeDefinition(
2062 cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
2063 !cmSystemTools::GetErrorOccurredFlag()) {
2064 // The compiler uses the MSVC ABI so it needs a known runtime library.
2065 this->IssueMessage(MessageType::FATAL_ERROR,
2066 cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
2067 *msvcDebugInformationFormat,
2068 "' not known for this ", lang,
2075 void cmLocalGenerator::AddLanguageFlagsForLinking(
2076 std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
2077 const std::string& config)
2079 if (this->Makefile->IsOn("CMAKE_" + lang +
2080 "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
2081 // This toolchain requires use of the language standard flag
2082 // when linking in order to use the matching standard library.
2083 // FIXME: If CMake gains an abstraction for standard library
2084 // selection, this will have to be reconciled with it.
2085 this->AddCompilerRequirementFlag(flags, target, lang, config);
2088 this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
2090 if (target->IsIPOEnabled(lang, config)) {
2091 this->AppendFeatureOptions(flags, lang, "IPO");
2095 cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
2096 const std::string& name) const
2098 auto imported = this->ImportedGeneratorTargets.find(name);
2099 if (imported != this->ImportedGeneratorTargets.end()) {
2100 return imported->second;
2103 // find local alias to imported target
2104 auto aliased = this->AliasTargets.find(name);
2105 if (aliased != this->AliasTargets.end()) {
2106 imported = this->ImportedGeneratorTargets.find(aliased->second);
2107 if (imported != this->ImportedGeneratorTargets.end()) {
2108 return imported->second;
2112 if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
2116 return this->GetGlobalGenerator()->FindGeneratorTarget(name);
2119 bool cmLocalGenerator::GetRealDependency(const std::string& inName,
2120 const std::string& config,
2123 // Older CMake code may specify the dependency using the target
2124 // output file rather than the target name. Such code would have
2125 // been written before there was support for target properties that
2126 // modify the name so stripping down to just the file name should
2127 // produce the target name in this case.
2128 std::string name = cmSystemTools::GetFilenameName(inName);
2130 // If the input name is the empty string, there is no real
2131 // dependency. Short-circuit the other checks:
2135 if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
2136 name = cmSystemTools::GetFilenameWithoutLastExtension(name);
2139 // Look for a CMake target with the given name.
2140 if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
2141 // make sure it is not just a coincidence that the target name
2142 // found is part of the inName
2143 if (cmSystemTools::FileIsFullPath(inName)) {
2144 std::string tLocation;
2145 if (target->GetType() >= cmStateEnums::EXECUTABLE &&
2146 target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
2147 tLocation = target->GetLocation(config);
2148 tLocation = cmSystemTools::GetFilenamePath(tLocation);
2149 tLocation = cmSystemTools::CollapseFullPath(tLocation);
2151 std::string depLocation =
2152 cmSystemTools::GetFilenamePath(std::string(inName));
2153 depLocation = cmSystemTools::CollapseFullPath(depLocation);
2154 if (depLocation != tLocation) {
2155 // it is a full path to a depend that has the same name
2156 // as a target but is in a different location so do not use
2157 // the target as the depend
2162 switch (target->GetType()) {
2163 case cmStateEnums::EXECUTABLE:
2164 case cmStateEnums::STATIC_LIBRARY:
2165 case cmStateEnums::SHARED_LIBRARY:
2166 case cmStateEnums::MODULE_LIBRARY:
2167 case cmStateEnums::UNKNOWN_LIBRARY:
2168 dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
2171 case cmStateEnums::OBJECT_LIBRARY:
2172 // An object library has no single file on which to depend.
2173 // This was listed to get the target-level dependency.
2174 case cmStateEnums::INTERFACE_LIBRARY:
2175 // An interface library has no file on which to depend.
2176 // This was listed to get the target-level dependency.
2177 case cmStateEnums::UTILITY:
2178 case cmStateEnums::GLOBAL_TARGET:
2179 // A utility target has no file on which to depend. This was listed
2180 // only to get the target-level dependency.
2185 // The name was not that of a CMake target. It must name a file.
2186 if (cmSystemTools::FileIsFullPath(inName)) {
2187 // This is a full path. Return it as given.
2192 // Check for a source file in this directory that matches the
2194 if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
2195 dep = sf->ResolveFullPath();
2199 // Treat the name as relative to the source directory in which it
2201 dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
2203 // If the in-source path does not exist, assume it instead lives in the
2204 // binary directory.
2205 if (!cmSystemTools::FileExists(dep)) {
2206 dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
2209 dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
2214 void cmLocalGenerator::AddSharedFlags(std::string& flags,
2215 const std::string& lang, bool shared)
2217 std::string flagsVar;
2219 // Add flags for dealing with shared libraries for this language.
2221 this->AppendFlags(flags,
2222 this->Makefile->GetSafeDefinition(
2223 cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
2227 void cmLocalGenerator::AddCompilerRequirementFlag(
2228 std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
2229 const std::string& config)
2231 cmStandardLevelResolver standardResolver(this->Makefile);
2233 std::string const& optionFlagDef =
2234 standardResolver.GetCompileOptionDef(target, lang, config);
2235 if (!optionFlagDef.empty()) {
2236 cmValue opt = target->Target->GetMakefile()->GetDefinition(optionFlagDef);
2238 std::vector<std::string> optVec = cmExpandedList(*opt);
2239 for (std::string const& i : optVec) {
2240 this->AppendFlagEscape(flags, i);
2246 static void AddVisibilityCompileOption(std::string& flags,
2247 cmGeneratorTarget const* target,
2248 cmLocalGenerator* lg,
2249 const std::string& lang,
2250 std::string* warnCMP0063)
2252 std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
2253 cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
2257 std::string flagDefine = lang + "_VISIBILITY_PRESET";
2259 cmValue prop = target->GetProperty(flagDefine);
2264 *warnCMP0063 += " " + flagDefine + "\n";
2267 if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
2268 (*prop != "internal")) {
2269 std::ostringstream e;
2270 e << "Target " << target->GetName() << " uses unsupported value \""
2271 << *prop << "\" for " << flagDefine << "."
2272 << " The supported values are: default, hidden, protected, and "
2274 cmSystemTools::Error(e.str());
2277 std::string option = *opt + *prop;
2278 lg->AppendFlags(flags, option);
2281 static void AddInlineVisibilityCompileOption(std::string& flags,
2282 cmGeneratorTarget const* target,
2283 cmLocalGenerator* lg,
2284 std::string* warnCMP0063,
2285 const std::string& lang)
2287 std::string compileOption =
2288 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
2289 cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
2294 bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
2299 *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
2302 lg->AppendFlags(flags, *opt);
2305 void cmLocalGenerator::AddVisibilityPresetFlags(
2306 std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
2312 std::string warnCMP0063;
2313 std::string* pWarnCMP0063 = nullptr;
2314 if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
2315 target->GetType() != cmStateEnums::MODULE_LIBRARY &&
2316 !target->IsExecutableWithExports()) {
2317 switch (target->GetPolicyStatusCMP0063()) {
2318 case cmPolicies::OLD:
2320 case cmPolicies::WARN:
2321 pWarnCMP0063 = &warnCMP0063;
2328 AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
2330 if (lang == "CXX" || lang == "OBJCXX") {
2331 AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
2334 if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
2335 std::ostringstream w;
2336 /* clang-format off */
2338 cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
2339 "Target \"" << target->GetName() << "\" of "
2340 "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
2341 "has the following visibility properties set for " << lang << ":\n" <<
2343 "For compatibility CMake is not honoring them for this target.";
2344 /* clang-format on */
2345 target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
2346 MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
2350 void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
2351 cmGeneratorTarget const* target,
2352 std::string const& lang,
2353 const std::string& config)
2355 int targetType = target->GetType();
2357 bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
2358 (targetType == cmStateEnums::MODULE_LIBRARY));
2360 if (this->GetShouldUseOldFlags(shared, lang)) {
2361 this->AddSharedFlags(flags, lang, shared);
2363 if (target->GetLinkInterfaceDependentBoolProperty(
2364 "POSITION_INDEPENDENT_CODE", config)) {
2365 this->AddPositionIndependentFlags(flags, lang, targetType);
2368 this->AppendFeatureOptions(flags, lang, "DLL");
2373 bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
2374 const std::string& lang) const
2376 std::string originalFlags =
2377 this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
2379 std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
2380 std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
2382 if (flags != originalFlags) {
2383 switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
2384 case cmPolicies::WARN: {
2385 std::ostringstream e;
2386 e << "Variable " << flagsVar
2387 << " has been modified. CMake "
2388 "will ignore the POSITION_INDEPENDENT_CODE target property "
2390 "shared libraries and will use the "
2393 "instead. This may cause errors if the original content of "
2394 << flagsVar << " was removed.\n"
2395 << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
2397 this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
2400 case cmPolicies::OLD:
2402 case cmPolicies::REQUIRED_IF_USED:
2403 case cmPolicies::REQUIRED_ALWAYS:
2404 case cmPolicies::NEW:
2412 void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
2413 std::string const& lang,
2416 std::string picFlags;
2418 if (targetType == cmStateEnums::EXECUTABLE) {
2419 picFlags = this->Makefile->GetSafeDefinition(
2420 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
2422 if (picFlags.empty()) {
2423 picFlags = this->Makefile->GetSafeDefinition(
2424 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
2426 if (!picFlags.empty()) {
2427 std::vector<std::string> options = cmExpandedList(picFlags);
2428 for (std::string const& o : options) {
2429 this->AppendFlagEscape(flags, o);
2434 void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
2435 const std::string& lang)
2437 cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
2439 std::string colorFlagName;
2442 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
2445 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
2448 std::vector<std::string> options;
2449 this->Makefile->GetDefExpandList(colorFlagName, options);
2451 for (std::string const& option : options) {
2452 this->AppendFlagEscape(flags, option);
2457 void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
2458 const std::string& var,
2459 const std::string& config)
2461 // Add the flags from the variable itself.
2462 this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
2463 // Add the flags from the build-type specific variable.
2464 if (!config.empty()) {
2465 const std::string flagsVar =
2466 cmStrCat(var, '_', cmSystemTools::UpperCase(config));
2467 this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
2471 void cmLocalGenerator::AppendFlags(std::string& flags,
2472 const std::string& newFlags) const
2474 bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
2476 if (!newFlags.empty() && !allSpaces) {
2477 if (!flags.empty()) {
2484 void cmLocalGenerator::AppendFlags(
2485 std::string& flags, const std::vector<BT<std::string>>& newFlags) const
2487 for (BT<std::string> const& flag : newFlags) {
2488 this->AppendFlags(flags, flag.Value);
2492 void cmLocalGenerator::AppendFlagEscape(std::string& flags,
2493 const std::string& rawFlag) const
2497 this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
2500 void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
2502 std::vector<std::string> enabledLanguages =
2503 this->GetState()->GetEnabledLanguages();
2504 if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
2505 enabledLanguages.end()) {
2509 cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
2510 assert(ispcHeaderSuffixProp);
2512 std::vector<std::string> ispcArchSuffixes =
2513 detail::ComputeISPCObjectSuffixes(target);
2514 const bool extra_objects = (ispcArchSuffixes.size() > 1);
2516 std::vector<std::string> configsList =
2517 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
2518 for (std::string const& config : configsList) {
2520 std::string rootObjectDir = target->GetObjectDirectory(config);
2521 std::string headerDir = rootObjectDir;
2522 if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
2523 headerDir = cmSystemTools::CollapseFullPath(
2524 cmStrCat(this->GetBinaryDirectory(), '/', *prop));
2527 std::vector<cmSourceFile*> sources;
2528 target->GetSourceFiles(sources, config);
2530 // build up the list of ispc headers and extra objects that this target is
2532 for (cmSourceFile const* sf : sources) {
2533 // Generate this object file's rule file.
2534 const std::string& lang = sf->GetLanguage();
2535 if (lang == "ISPC") {
2536 std::string const& objectName = target->GetObjectName(sf);
2538 // Drop both ".obj" and the source file extension
2539 std::string ispcSource =
2540 cmSystemTools::GetFilenameWithoutLastExtension(objectName);
2542 cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
2545 cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
2546 target->AddISPCGeneratedHeader(headerPath, config);
2547 if (extra_objects) {
2548 std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
2549 objectName, rootObjectDir, ispcArchSuffixes);
2550 target->AddISPCGeneratedObject(std::move(objs), config);
2557 void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
2559 std::vector<std::string> configsList =
2560 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
2562 for (std::string const& config : configsList) {
2563 // FIXME: Refactor collection of sources to not evaluate object
2565 std::vector<cmSourceFile*> sources;
2566 target->GetSourceFiles(sources, config);
2568 const std::string configUpper = cmSystemTools::UpperCase(config);
2569 static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
2572 std::set<std::string> pchLangSet;
2573 if (this->GetGlobalGenerator()->IsXcode()) {
2574 for (const std::string& lang : langs) {
2575 const std::string pchHeader = target->GetPchHeader(config, lang, "");
2576 if (!pchHeader.empty()) {
2577 pchLangSet.emplace(lang);
2582 for (const std::string& lang : langs) {
2583 auto langSources = std::count_if(
2584 sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
2585 return lang == sf->GetLanguage() &&
2586 !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
2588 if (langSources == 0) {
2592 std::vector<std::string> architectures;
2593 if (!this->GetGlobalGenerator()->IsXcode()) {
2594 target->GetAppleArchs(config, architectures);
2596 if (architectures.empty()) {
2597 architectures.emplace_back();
2599 std::string useMultiArchPch;
2600 for (const std::string& arch : architectures) {
2601 const std::string pchHeader =
2602 target->GetPchHeader(config, lang, arch);
2603 if (!pchHeader.empty()) {
2604 useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
2605 ";-include", pchHeader);
2609 if (!useMultiArchPch.empty()) {
2611 target->Target->AppendProperty(
2612 cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
2613 cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
2617 for (const std::string& arch : architectures) {
2618 const std::string pchSource = target->GetPchSource(config, lang, arch);
2619 const std::string pchHeader = target->GetPchHeader(config, lang, arch);
2621 if (pchSource.empty() || pchHeader.empty()) {
2622 if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
2623 for (auto* sf : sources) {
2624 const auto sourceLanguage = sf->GetLanguage();
2625 if (!sourceLanguage.empty() &&
2626 pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
2627 sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
2634 cmValue pchExtension =
2635 this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
2637 if (pchExtension.IsEmpty()) {
2642 target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
2644 auto* pch_sf = this->Makefile->GetOrCreateSource(
2645 pchSource, false, cmSourceFileLocationKind::Known);
2647 if (!this->GetGlobalGenerator()->IsXcode()) {
2649 target->AddSource(pchSource, true);
2652 const std::string pchFile = target->GetPchFile(config, lang, arch);
2654 // Exclude the pch files from linking
2655 if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
2657 pch_sf->AppendProperty(
2659 cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
2662 this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
2664 if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
2666 const std::string compilerId =
2667 this->Makefile->GetSafeDefinition(
2668 cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
2670 const std::string compilerVersion =
2671 this->Makefile->GetSafeDefinition(
2672 cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
2674 const std::string langFlags =
2675 this->Makefile->GetSafeDefinition(
2676 cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
2678 bool editAndContinueDebugInfo = false;
2679 bool programDatabaseDebugInfo = false;
2680 cm::optional<std::string> msvcDebugInformationFormat =
2681 this->GetMSVCDebugFormatName(config, target);
2682 if (msvcDebugInformationFormat &&
2683 !msvcDebugInformationFormat->empty()) {
2684 editAndContinueDebugInfo =
2685 *msvcDebugInformationFormat == "EditAndContinue";
2686 programDatabaseDebugInfo =
2687 *msvcDebugInformationFormat == "ProgramDatabase";
2689 editAndContinueDebugInfo =
2690 langFlags.find("/ZI") != std::string::npos ||
2691 langFlags.find("-ZI") != std::string::npos;
2692 programDatabaseDebugInfo =
2693 langFlags.find("/Zi") != std::string::npos ||
2694 langFlags.find("-Zi") != std::string::npos;
2697 // MSVC 2008 is producing both .pdb and .idb files with /Zi.
2698 bool msvc2008OrLess =
2699 cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
2700 compilerVersion, "16.0") &&
2701 compilerId == "MSVC";
2702 // but not when used via toolset -Tv90
2703 if (this->Makefile->GetSafeDefinition(
2704 "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
2705 msvc2008OrLess = false;
2708 if (editAndContinueDebugInfo || msvc2008OrLess) {
2709 this->CopyPchCompilePdb(config, target, *ReuseFrom,
2710 reuseTarget, { ".pdb", ".idb" });
2711 } else if (programDatabaseDebugInfo) {
2712 this->CopyPchCompilePdb(config, target, *ReuseFrom,
2713 reuseTarget, { ".pdb" });
2717 // Link to the pch object file
2718 std::string pchSourceObj =
2719 reuseTarget->GetPchFileObject(config, lang, arch);
2721 if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
2722 std::string linkerProperty = "LINK_FLAGS_";
2723 if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
2724 linkerProperty = "STATIC_LIBRARY_FLAGS_";
2726 target->Target->AppendProperty(
2727 cmStrCat(linkerProperty, configUpper),
2729 this->ConvertToOutputFormat(pchSourceObj, SHELL)),
2731 } else if (reuseTarget->GetType() ==
2732 cmStateEnums::OBJECT_LIBRARY) {
2733 // FIXME: This can propagate more than one level, unlike
2734 // the rest of the object files in an object library.
2735 // Find another way to do this.
2736 target->Target->AppendProperty(
2737 "INTERFACE_LINK_LIBRARIES",
2738 cmStrCat("$<$<CONFIG:", config,
2739 ">:$<LINK_ONLY:", pchSourceObj, ">>"));
2740 // We updated the link interface, so ensure it is recomputed.
2741 target->ClearLinkInterfaceCache();
2745 pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
2748 // Add pchHeader to source files, which will
2749 // be grouped as "Precompile Header File"
2750 auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
2751 pchHeader, false, cmSourceFileLocationKind::Known);
2753 pchHeader_sf->ResolveFullPath(&err);
2755 std::ostringstream msg;
2756 msg << "Unable to resolve full path of PCH-header '" << pchHeader
2757 << "' assigned to target " << target->GetName()
2758 << ", although its path is supposed to be known!";
2759 this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
2761 target->AddSource(pchHeader);
2768 void cmLocalGenerator::CopyPchCompilePdb(
2769 const std::string& config, cmGeneratorTarget* target,
2770 const std::string& ReuseFrom, cmGeneratorTarget* reuseTarget,
2771 const std::vector<std::string>& extensions)
2773 const std::string pdb_prefix =
2774 this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
2776 const std::string target_compile_pdb_dir =
2777 cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
2778 target->GetName(), ".dir/");
2780 const std::string copy_script = cmStrCat(
2781 target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
2782 cmGeneratedFileStream file(copy_script);
2784 file << "# CMake generated file\n";
2786 file << "# The compiler generated pdb file needs to be written to disk\n"
2787 << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
2788 << "# the pdb file is ready to be copied.\n\n";
2790 for (auto const& extension : extensions) {
2791 const std::string from_file =
2792 cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
2793 "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
2795 const std::string to_dir =
2796 cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
2797 target->GetName(), ".dir/${PDB_PREFIX}");
2799 const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
2801 std::string dest_file = to_file;
2803 std::string const& prefix = target->GetSafeProperty("PREFIX");
2804 if (!prefix.empty()) {
2805 dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
2808 file << "foreach(retry RANGE 1 30)\n";
2809 file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
2810 << dest_file << "\" OR NOT \"" << dest_file << " \" IS_NEWER_THAN \""
2811 << from_file << "\"))\n";
2812 file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
2813 file << " \"" << from_file << "\""
2814 << " \"" << to_dir << "\" RESULT_VARIABLE result "
2815 << " ERROR_QUIET)\n";
2816 file << " if (NOT result EQUAL 0)\n"
2817 << " execute_process(COMMAND ${CMAKE_COMMAND}"
2820 if (!prefix.empty()) {
2821 file << " file(REMOVE \"" << dest_file << "\")\n";
2822 file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
2824 file << " break()\n"
2826 file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
2827 << " execute_process(COMMAND ${CMAKE_COMMAND}"
2830 file << "endforeach()\n";
2833 auto configGenex = [&](cm::string_view expr) -> std::string {
2834 if (this->GetGlobalGenerator()->IsMultiConfig()) {
2835 return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
2837 return std::string(expr);
2840 cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
2841 { configGenex(cmSystemTools::GetCMakeCommand()),
2842 configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
2843 configGenex(copy_script) });
2845 const char* no_message = "";
2847 std::vector<std::string> outputs;
2848 outputs.push_back(configGenex(
2849 cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
2851 auto cc = cm::make_unique<cmCustomCommand>();
2852 cc->SetCommandLines(commandLines);
2853 cc->SetComment(no_message);
2854 cc->SetCMP0116Status(cmPolicies::NEW);
2855 cc->SetStdPipesUTF8(true);
2857 if (this->GetGlobalGenerator()->IsVisualStudio()) {
2858 cc->SetByproducts(outputs);
2859 this->AddCustomCommandToTarget(
2860 target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
2861 cmObjectLibraryCommands::Accept);
2863 cc->SetOutputs(outputs);
2864 cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
2867 target->AddSource(copy_rule->ResolveFullPath());
2871 target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
2872 target_compile_pdb_dir);
2875 cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
2876 std::string const& config, cmGeneratorTarget const* target)
2878 // MSVC debug information format selection is activated by the presence
2879 // of a default whether or not it is overridden by a property.
2880 cm::optional<std::string> msvcDebugInformationFormat;
2881 cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
2882 "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
2883 if (cmNonempty(msvcDebugInformationFormatDefault)) {
2884 cmValue msvcDebugInformationFormatValue =
2885 target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
2886 if (!msvcDebugInformationFormatValue) {
2887 msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
2889 msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
2890 *msvcDebugInformationFormatValue, this, config, target);
2892 return msvcDebugInformationFormat;
2897 inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
2898 std::string const& filename)
2900 target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
2901 sf->SetProperty("UNITY_SOURCE_FILE", filename);
2905 cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
2906 cmGeneratorTarget* target, std::vector<std::string> const& configs,
2907 cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
2908 cmValue beforeInclude, cmValue afterInclude, std::string filename) const
2910 cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
2911 cmGeneratedFileStream file(
2912 filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
2913 file.SetCopyIfDifferent(true);
2914 file << "/* generated by CMake */\n\n";
2916 bool perConfig = false;
2917 for (UnityBatchedSource const& ubs : sources) {
2918 cm::optional<std::string> cond;
2919 if (ubs.Configs.size() != configs.size()) {
2921 cond = std::string();
2922 cm::string_view sep;
2923 for (size_t ci : ubs.Configs) {
2924 cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
2925 cmSystemTools::UpperCase(configs[ci]), ")");
2929 RegisterUnitySources(target, ubs.Source, filename);
2930 WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
2931 beforeInclude, afterInclude, uniqueIdName);
2934 return UnitySource(std::move(filename), perConfig);
2937 void cmLocalGenerator::WriteUnitySourceInclude(
2938 std::ostream& unity_file, cm::optional<std::string> const& cond,
2939 std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
2940 cmValue uniqueIdName) const
2943 unity_file << "#if " << *cond << "\n";
2946 if (cmNonempty(uniqueIdName)) {
2947 std::string pathToHash;
2948 auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
2949 return (cmSystemTools::ComparePath(a, b) ||
2950 cmSystemTools::IsSubDirectory(a, b));
2952 const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
2953 if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
2954 pathToHash = "BLD_" +
2955 cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
2956 } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
2957 pathToHash = "SRC_" +
2958 cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
2960 pathToHash = "ABS_" + sf_full_path;
2962 unity_file << "/* " << pathToHash << " */\n"
2963 << "#undef " << *uniqueIdName << "\n"
2964 << "#define " << *uniqueIdName << " unity_"
2965 #ifndef CMAKE_BOOTSTRAP
2966 << cmSystemTools::ComputeStringMD5(pathToHash) << "\n"
2971 if (beforeInclude) {
2972 unity_file << *beforeInclude << "\n";
2975 unity_file << "#include \"" << sf_full_path << "\"\n";
2978 unity_file << *afterInclude << "\n";
2981 unity_file << "#endif\n";
2986 std::vector<cmLocalGenerator::UnitySource>
2987 cmLocalGenerator::AddUnityFilesModeAuto(
2988 cmGeneratorTarget* target, std::string const& lang,
2989 std::vector<std::string> const& configs,
2990 std::vector<UnityBatchedSource> const& filtered_sources,
2991 cmValue beforeInclude, cmValue afterInclude,
2992 std::string const& filename_base, size_t batchSize)
2994 if (batchSize == 0) {
2995 batchSize = filtered_sources.size();
2998 std::vector<UnitySource> unity_files;
2999 for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
3000 itemsLeft > 0; itemsLeft -= chunk, ++batch) {
3002 chunk = std::min(itemsLeft, batchSize);
3004 std::string filename = cmStrCat(filename_base, "unity_", batch,
3005 (lang == "C") ? "_c.c" : "_cxx.cxx");
3006 auto const begin = filtered_sources.begin() + batch * batchSize;
3007 auto const end = begin + chunk;
3008 unity_files.emplace_back(this->WriteUnitySource(
3009 target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
3010 std::move(filename)));
3015 std::vector<cmLocalGenerator::UnitySource>
3016 cmLocalGenerator::AddUnityFilesModeGroup(
3017 cmGeneratorTarget* target, std::string const& lang,
3018 std::vector<std::string> const& configs,
3019 std::vector<UnityBatchedSource> const& filtered_sources,
3020 cmValue beforeInclude, cmValue afterInclude,
3021 std::string const& filename_base)
3023 std::vector<UnitySource> unity_files;
3025 // sources organized by group name. Drop any source
3027 std::unordered_map<std::string, std::vector<UnityBatchedSource>>
3029 for (UnityBatchedSource const& ubs : filtered_sources) {
3030 if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
3031 auto i = explicit_mapping.find(*value);
3032 if (i == explicit_mapping.end()) {
3033 std::vector<UnityBatchedSource> sources{ ubs };
3034 explicit_mapping.emplace(*value, std::move(sources));
3036 i->second.emplace_back(ubs);
3041 for (auto const& item : explicit_mapping) {
3042 auto const& name = item.first;
3043 std::string filename = cmStrCat(filename_base, "unity_", name,
3044 (lang == "C") ? "_c.c" : "_cxx.cxx");
3045 unity_files.emplace_back(this->WriteUnitySource(
3046 target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
3047 std::move(filename)));
3053 void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
3055 if (!target->GetPropertyAsBool("UNITY_BUILD")) {
3059 std::vector<UnityBatchedSource> unitySources;
3061 std::vector<std::string> configs =
3062 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
3064 std::map<cmSourceFile const*, size_t> index;
3066 for (size_t ci = 0; ci < configs.size(); ++ci) {
3067 // FIXME: Refactor collection of sources to not evaluate object libraries.
3068 std::vector<cmSourceFile*> sources;
3069 target->GetSourceFiles(sources, configs[ci]);
3070 for (cmSourceFile* sf : sources) {
3071 auto mi = index.find(sf);
3072 if (mi == index.end()) {
3073 unitySources.emplace_back(sf);
3074 std::map<cmSourceFile const*, size_t>::value_type entry(
3075 sf, unitySources.size() - 1);
3076 mi = index.insert(entry).first;
3078 unitySources[mi->second].Configs.emplace_back(ci);
3082 std::string filename_base =
3083 cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
3084 target->GetName(), ".dir/Unity/");
3086 cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
3087 const size_t unityBatchSize = batchSizeString
3088 ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
3091 cmValue beforeInclude =
3092 target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
3093 cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
3094 cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
3096 for (std::string lang : { "C", "CXX" }) {
3097 std::vector<UnityBatchedSource> filtered_sources;
3098 std::copy_if(unitySources.begin(), unitySources.end(),
3099 std::back_inserter(filtered_sources),
3100 [&](UnityBatchedSource const& ubs) -> bool {
3101 cmSourceFile* sf = ubs.Source;
3102 return sf->GetLanguage() == lang &&
3103 !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
3104 !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
3105 !sf->GetProperty("COMPILE_OPTIONS") &&
3106 !sf->GetProperty("COMPILE_DEFINITIONS") &&
3107 !sf->GetProperty("COMPILE_FLAGS") &&
3108 !sf->GetProperty("INCLUDE_DIRECTORIES");
3111 std::vector<UnitySource> unity_files;
3112 if (!unityMode || *unityMode == "BATCH") {
3113 unity_files = AddUnityFilesModeAuto(
3114 target, lang, configs, filtered_sources, beforeInclude, afterInclude,
3115 filename_base, unityBatchSize);
3116 } else if (unityMode && *unityMode == "GROUP") {
3118 AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
3119 beforeInclude, afterInclude, filename_base);
3121 // unity mode is set to an unsupported value
3122 std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
3123 " assigned to target " + target->GetName() +
3124 ". Acceptable values are BATCH and GROUP.");
3125 this->IssueMessage(MessageType::FATAL_ERROR, e);
3128 for (UnitySource const& file : unity_files) {
3129 auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
3130 target->AddSource(file.Path, true);
3131 unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
3132 unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
3133 if (file.PerConfig) {
3134 unity->SetProperty("COMPILE_DEFINITIONS",
3135 "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
3141 void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
3142 cmGeneratorTarget* target,
3143 const std::string& config,
3144 const std::string& lang)
3146 if (!target->IsIPOEnabled(lang, config)) {
3150 switch (target->GetType()) {
3151 case cmStateEnums::EXECUTABLE:
3152 case cmStateEnums::SHARED_LIBRARY:
3153 case cmStateEnums::MODULE_LIBRARY:
3159 const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
3160 cmValue rawFlagsList = this->Makefile->GetDefinition(name);
3161 if (!rawFlagsList) {
3165 std::vector<std::string> flagsList = cmExpandedList(*rawFlagsList);
3166 for (std::string const& o : flagsList) {
3167 this->AppendFlagEscape(flags, o);
3171 void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
3172 std::string& flags, cmGeneratorTarget* target, const std::string& config,
3173 const std::string& lang)
3175 // For now, only EXECUTABLE is concerned
3176 if (target->GetType() != cmStateEnums::EXECUTABLE) {
3180 const char* PICValue = target->GetLinkPIEProperty(config);
3181 if (PICValue == nullptr) {
3182 // POSITION_INDEPENDENT_CODE is not set
3186 const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
3188 std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
3189 if (cmIsOff(this->Makefile->GetDefinition(supported))) {
3193 std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
3195 auto pieFlags = this->Makefile->GetSafeDefinition(name);
3196 if (pieFlags.empty()) {
3200 std::vector<std::string> flagsList = cmExpandedList(pieFlags);
3201 for (const auto& flag : flagsList) {
3202 this->AppendFlagEscape(flags, flag);
3206 void cmLocalGenerator::AppendModuleDefinitionFlag(
3207 std::string& flags, cmGeneratorTarget const* target,
3208 cmLinkLineComputer* linkLineComputer, std::string const& config)
3210 cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
3211 target->GetModuleDefinitionInfo(config);
3212 if (!mdi || mdi->DefFile.empty()) {
3216 cmValue defFileFlag =
3217 this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
3222 // Append the flag and value. Use ConvertToLinkReference to help
3223 // vs6's "cl -link" pass it to the linker.
3225 cmStrCat(*defFileFlag,
3226 this->ConvertToOutputFormat(
3227 linkLineComputer->ConvertToLinkReference(mdi->DefFile),
3228 cmOutputConverter::SHELL));
3229 this->AppendFlags(flags, flag);
3232 bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
3233 const cmGeneratorTarget* target,
3234 const std::string& lang)
3236 auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
3237 (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
3238 target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
3239 target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
3242 const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
3243 cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
3244 useLWYU = !lwyuFlag.empty();
3247 std::vector<BT<std::string>> lwyuOpts;
3248 lwyuOpts.emplace_back(lwyuFlag);
3249 this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
3256 void cmLocalGenerator::AppendCompileOptions(std::string& options,
3257 std::string const& options_list,
3258 const char* regex) const
3260 // Short-circuit if there are no options.
3261 if (options_list.empty()) {
3265 // Expand the list of options.
3266 std::vector<std::string> options_vec = cmExpandedList(options_list);
3267 this->AppendCompileOptions(options, options_vec, regex);
3270 void cmLocalGenerator::AppendCompileOptions(
3271 std::string& options, const std::vector<std::string>& options_vec,
3272 const char* regex) const
3274 if (regex != nullptr) {
3275 // Filter flags upon specified reges.
3276 cmsys::RegularExpression r(regex);
3278 for (std::string const& opt : options_vec) {
3280 this->AppendFlagEscape(options, opt);
3284 for (std::string const& opt : options_vec) {
3285 this->AppendFlagEscape(options, opt);
3290 void cmLocalGenerator::AppendCompileOptions(
3291 std::vector<BT<std::string>>& options,
3292 const std::vector<BT<std::string>>& options_vec, const char* regex) const
3294 if (regex != nullptr) {
3295 // Filter flags upon specified regular expressions.
3296 cmsys::RegularExpression r(regex);
3298 for (BT<std::string> const& opt : options_vec) {
3299 if (r.find(opt.Value)) {
3301 this->AppendFlagEscape(flag, opt.Value);
3302 options.emplace_back(std::move(flag), opt.Backtrace);
3306 for (BT<std::string> const& opt : options_vec) {
3308 this->AppendFlagEscape(flag, opt.Value);
3309 options.emplace_back(std::move(flag), opt.Backtrace);
3314 void cmLocalGenerator::AppendIncludeDirectories(
3315 std::vector<std::string>& includes, const std::string& includes_list,
3316 const cmSourceFile& sourceFile) const
3318 // Short-circuit if there are no includes.
3319 if (includes_list.empty()) {
3323 // Expand the list of includes.
3324 std::vector<std::string> includes_vec = cmExpandedList(includes_list);
3325 this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
3328 void cmLocalGenerator::AppendIncludeDirectories(
3329 std::vector<std::string>& includes,
3330 const std::vector<std::string>& includes_vec,
3331 const cmSourceFile& sourceFile) const
3333 std::unordered_set<std::string> uniqueIncludes;
3335 for (const std::string& include : includes_vec) {
3336 if (!cmSystemTools::FileIsFullPath(include)) {
3337 std::ostringstream e;
3338 e << "Found relative path while evaluating include directories of "
3340 << sourceFile.GetLocation().GetName() << "\":\n \"" << include
3343 this->IssueMessage(MessageType::FATAL_ERROR, e.str());
3347 std::string inc = include;
3349 if (!cmIsOff(inc)) {
3350 cmSystemTools::ConvertToUnixSlashes(inc);
3353 if (uniqueIncludes.insert(inc).second) {
3354 includes.push_back(std::move(inc));
3359 void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
3360 std::string const& defines_list) const
3362 std::set<BT<std::string>> tmp;
3363 this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
3364 for (BT<std::string> const& i : tmp) {
3365 defines.emplace(i.Value);
3369 void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
3370 std::string const& defines_list) const
3372 // Short-circuit if there are no definitions.
3373 if (defines_list.empty()) {
3377 // Expand the list of definitions.
3378 this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
3381 void cmLocalGenerator::AppendDefines(
3382 std::set<BT<std::string>>& defines,
3383 const std::vector<BT<std::string>>& defines_vec) const
3385 for (BT<std::string> const& d : defines_vec) {
3386 // Skip unsupported definitions.
3387 if (!this->CheckDefinition(d.Value)) {
3394 void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
3395 std::string& definesString,
3396 const std::string& lang)
3398 // Lookup the define flag for the current language.
3399 std::string dflag = "-D";
3400 if (!lang.empty()) {
3402 this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
3403 if (cmNonempty(df)) {
3407 const char* itemSeparator = definesString.empty() ? "" : " ";
3408 for (std::string const& define : defines) {
3409 // Append the definition with proper escaping.
3410 std::string def = dflag;
3411 if (this->GetState()->UseWatcomWMake()) {
3412 // The Watcom compiler does its own command line parsing instead
3413 // of using the windows shell rules. Definitions are one of
3415 // -DNAME=<cpp-token>
3416 // -DNAME="c-string with spaces and other characters(?@#$)"
3418 // Watcom will properly parse each of these cases from the
3419 // command line without any escapes. However we still have to
3420 // get the '$' and '#' characters through WMake as '$$' and
3422 for (char c : define) {
3423 if (c == '$' || c == '#') {
3429 // Make the definition appear properly on the command line. Use
3430 // -DNAME="value" instead of -D"NAME=value" for historical reasons.
3431 std::string::size_type eq = define.find('=');
3432 def += define.substr(0, eq);
3433 if (eq != std::string::npos) {
3435 def += this->EscapeForShell(define.substr(eq + 1), true);
3438 definesString += itemSeparator;
3439 itemSeparator = " ";
3440 definesString += def;
3444 void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
3445 const std::string& lang,
3446 const char* feature)
3448 cmValue optionList = this->Makefile->GetDefinition(
3449 cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
3451 std::vector<std::string> options = cmExpandedList(*optionList);
3452 for (std::string const& o : options) {
3453 this->AppendFlagEscape(flags, o);
3458 cmValue cmLocalGenerator::GetFeature(const std::string& feature,
3459 const std::string& config)
3461 std::string featureName = feature;
3462 // TODO: Define accumulation policy for features (prepend, append,
3463 // replace). Currently we always replace.
3464 if (!config.empty()) {
3466 featureName += cmSystemTools::UpperCase(config);
3468 cmStateSnapshot snp = this->StateSnapshot;
3469 while (snp.IsValid()) {
3470 if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
3473 snp = snp.GetBuildsystemDirectoryParent();
3478 std::string cmLocalGenerator::GetProjectName() const
3480 return this->StateSnapshot.GetProjectName();
3483 std::string cmLocalGenerator::ConstructComment(
3484 cmCustomCommandGenerator const& ccg, const char* default_comment) const
3486 // Check for a comment provided with the command.
3487 if (ccg.GetComment()) {
3488 return ccg.GetComment();
3491 // Construct a reasonable default comment if possible.
3492 if (!ccg.GetOutputs().empty()) {
3493 std::string comment;
3494 comment = "Generating ";
3495 const char* sep = "";
3496 for (std::string const& o : ccg.GetOutputs()) {
3498 comment += this->MaybeRelativeToCurBinDir(o);
3504 // Otherwise use the provided default.
3505 return default_comment;
3508 class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
3511 cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
3512 std::string const& dest, bool implib)
3513 : cmInstallTargetGenerator(
3514 t, dest, implib, "", std::vector<std::string>(), "Unspecified",
3515 cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
3522 void cmLocalGenerator::GenerateTargetInstallRules(
3523 std::ostream& os, const std::string& config,
3524 std::vector<std::string> const& configurationTypes)
3526 // Convert the old-style install specification from each target to
3527 // an install generator and run it.
3528 const auto& tgts = this->GetGeneratorTargets();
3529 for (const auto& l : tgts) {
3530 if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
3534 // Include the user-specified pre-install script for this target.
3535 if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
3536 cmInstallScriptGenerator g(*preinstall, false, "", false, false);
3537 g.Generate(os, config, configurationTypes);
3540 // Install this target if a destination is given.
3541 if (!l->Target->GetInstallPath().empty()) {
3542 // Compute the full install destination. Note that converting
3543 // to unix slashes also removes any trailing slash.
3544 // We also skip over the leading slash given by the user.
3545 std::string destination = l->Target->GetInstallPath().substr(1);
3546 cmSystemTools::ConvertToUnixSlashes(destination);
3547 if (destination.empty()) {
3551 // Generate the proper install generator for this target type.
3552 switch (l->GetType()) {
3553 case cmStateEnums::EXECUTABLE:
3554 case cmStateEnums::STATIC_LIBRARY:
3555 case cmStateEnums::MODULE_LIBRARY: {
3556 // Use a target install generator.
3557 cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
3559 g.Generate(os, config, configurationTypes);
3561 case cmStateEnums::SHARED_LIBRARY: {
3562 #if defined(_WIN32) || defined(__CYGWIN__)
3563 // Special code to handle DLL. Install the import library
3564 // to the normal destination and the DLL to the runtime
3566 cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
3568 g1.Generate(os, config, configurationTypes);
3569 // We also skip over the leading slash given by the user.
3570 destination = l->Target->GetRuntimeInstallPath().substr(1);
3571 cmSystemTools::ConvertToUnixSlashes(destination);
3572 cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
3574 g2.Generate(os, config, configurationTypes);
3576 // Use a target install generator.
3577 cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
3579 g.Generate(os, config, configurationTypes);
3587 // Include the user-specified post-install script for this target.
3588 if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
3589 cmInstallScriptGenerator g(*postinstall, false, "", false, false);
3590 g.Generate(os, config, configurationTypes);
3595 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
3596 static bool cmLocalGeneratorShortenObjectName(std::string& objName,
3597 std::string::size_type max_len)
3599 // Check if the path can be shortened using an md5 sum replacement for
3600 // a portion of the path.
3601 std::string::size_type md5Len = 32;
3602 std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
3603 std::string::size_type pos = objName.find('/', numExtraChars);
3604 if (pos == std::string::npos) {
3605 pos = objName.rfind('/', numExtraChars);
3606 if (pos == std::string::npos || pos <= md5Len) {
3611 // Replace the beginning of the path portion of the object name with
3613 cmCryptoHash md5(cmCryptoHash::AlgoMD5);
3614 std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
3615 cm::string_view(objName).substr(pos));
3618 // The object name is now shorter, check if it is short enough.
3619 return pos >= numExtraChars;
3622 bool cmLocalGeneratorCheckObjectName(std::string& objName,
3623 std::string::size_type dir_len,
3624 std::string::size_type max_total_len)
3626 // Enforce the maximum file name length if possible.
3627 std::string::size_type max_obj_len = max_total_len;
3628 if (dir_len < max_total_len) {
3629 max_obj_len = max_total_len - dir_len;
3630 if (objName.size() > max_obj_len) {
3631 // The current object file name is too long. Try to shorten it.
3632 return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
3634 // The object file name is short enough.
3637 // The build directory in which the object will be stored is
3638 // already too deep.
3643 std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
3644 const std::string& sin, std::string const& dir_max)
3646 // Look for an existing mapped name for this object file.
3647 auto it = this->UniqueObjectNamesMap.find(sin);
3649 // If no entry exists create one.
3650 if (it == this->UniqueObjectNamesMap.end()) {
3651 // Start with the original name.
3652 std::string ssin = sin;
3654 // Avoid full paths by removing leading slashes.
3655 ssin.erase(0, ssin.find_first_not_of('/'));
3657 // Avoid full paths by removing colons.
3658 std::replace(ssin.begin(), ssin.end(), ':', '_');
3660 // Avoid relative paths that go up the tree.
3661 cmSystemTools::ReplaceString(ssin, "../", "__/");
3664 std::replace(ssin.begin(), ssin.end(), ' ', '_');
3666 // Mangle the name if necessary.
3667 if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
3671 snprintf(rpstr, sizeof(rpstr), "_p_");
3672 cmSystemTools::ReplaceString(ssin, "+", rpstr);
3673 std::string sssin = sin;
3676 for (it = this->UniqueObjectNamesMap.begin();
3677 it != this->UniqueObjectNamesMap.end(); ++it) {
3678 if (it->second == ssin) {
3686 cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
3687 snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
3691 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
3692 if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
3693 this->ObjectPathMax)) {
3694 // Warn if this is the first time the path has been seen.
3695 if (this->ObjectMaxPathViolations.insert(dir_max).second) {
3696 std::ostringstream m;
3697 /* clang-format off */
3698 m << "The object file directory\n"
3699 << " " << dir_max << "\n"
3700 << "has " << dir_max.size() << " characters. "
3701 << "The maximum full path to an object file is "
3702 << this->ObjectPathMax << " characters "
3703 << "(see CMAKE_OBJECT_PATH_MAX). "
3705 << " " << ssin << "\n"
3706 << "cannot be safely placed under this directory. "
3707 << "The build may not work correctly.";
3708 /* clang-format on */
3709 this->IssueMessage(MessageType::WARNING, m.str());
3716 // Insert the newly mapped object file name.
3717 std::map<std::string, std::string>::value_type e(sin, ssin);
3718 it = this->UniqueObjectNamesMap.insert(e).first;
3721 // Return the map entry.
3725 void cmLocalGenerator::ComputeObjectFilenames(
3726 std::map<cmSourceFile const*, std::string>& /*unused*/,
3727 cmGeneratorTarget const* /*unused*/)
3731 bool cmLocalGenerator::IsWindowsShell() const
3733 return this->GetState()->UseWindowsShell();
3736 bool cmLocalGenerator::IsWatcomWMake() const
3738 return this->GetState()->UseWatcomWMake();
3741 bool cmLocalGenerator::IsMinGWMake() const
3743 return this->GetState()->UseMinGWMake();
3746 bool cmLocalGenerator::IsNMake() const
3748 return this->GetState()->UseNMake();
3751 bool cmLocalGenerator::IsNinjaMulti() const
3753 return this->GetState()->UseNinjaMulti();
3757 std::string relativeIfUnder(std::string const& top, std::string const& cur,
3758 std::string const& path)
3760 // Use a path relative to 'cur' if it can be expressed without
3761 // a `../` sequence that leaves 'top'.
3762 if (cmSystemTools::IsSubDirectory(path, cur) ||
3763 (cmSystemTools::IsSubDirectory(cur, top) &&
3764 cmSystemTools::IsSubDirectory(path, top))) {
3765 return cmSystemTools::ForceToRelativePath(cur, path);
3771 std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
3772 const cmSourceFile& source, std::string const& dir_max,
3773 bool* hasSourceExtension, char const* customOutputExtension)
3775 // Construct the object file name using the full path to the source
3776 // file which is its only unique identification.
3777 std::string const& fullPath = source.GetFullPath();
3779 // Try referencing the source relative to the source tree.
3780 std::string relFromSource = relativeIfUnder(
3781 this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
3782 assert(!relFromSource.empty());
3783 bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
3784 bool subSource = relSource && relFromSource[0] != '.';
3786 // Try referencing the source relative to the binary tree.
3787 std::string relFromBinary = relativeIfUnder(
3788 this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
3789 assert(!relFromBinary.empty());
3790 bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
3791 bool subBinary = relBinary && relFromBinary[0] != '.';
3793 // Select a nice-looking reference to the source file to construct
3794 // the object file name.
3795 std::string objectName;
3796 // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
3797 // NOLINTNEXTLINE(bugprone-branch-clone)
3798 if ((relSource && !relBinary) || (subSource && !subBinary)) {
3799 objectName = relFromSource;
3800 } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
3801 relFromBinary.length() < relFromSource.length()) {
3802 objectName = relFromBinary;
3804 objectName = relFromSource;
3807 // if it is still a full path check for the try compile case
3808 // try compile never have in source sources, and should not
3809 // have conflicting source file names in the same target
3810 if (cmSystemTools::FileIsFullPath(objectName)) {
3811 if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
3812 objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
3816 // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
3817 // we don't end up having:
3818 // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
3819 cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
3820 cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
3821 const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
3822 if (unitySourceFile || pchExtension || isPchObject) {
3824 customOutputExtension = pchExtension->c_str();
3827 cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
3828 if (var.find(objectName)) {
3829 objectName.erase(var.start(), var.end() - var.start());
3833 // Replace the original source file extension with the object file
3835 bool keptSourceExtension = true;
3836 if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
3837 // Decide whether this language wants to replace the source
3838 // extension with the object extension. For CMake 2.4
3839 // compatibility do this by default.
3840 bool replaceExt = this->NeedBackwardsCompatibility_2_4();
3842 std::string lang = source.GetLanguage();
3843 if (!lang.empty()) {
3844 replaceExt = this->Makefile->IsOn(
3845 cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
3849 // Remove the source extension if it is to be replaced.
3850 if (replaceExt || customOutputExtension) {
3851 keptSourceExtension = false;
3852 std::string::size_type dot_pos = objectName.rfind('.');
3853 if (dot_pos != std::string::npos) {
3854 objectName = objectName.substr(0, dot_pos);
3858 // Store the new extension.
3859 if (customOutputExtension) {
3860 objectName += customOutputExtension;
3862 objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
3865 if (hasSourceExtension) {
3866 *hasSourceExtension = keptSourceExtension;
3869 // Convert to a safe name.
3870 return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
3873 std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
3875 return source.GetLanguage();
3878 cmake* cmLocalGenerator::GetCMakeInstance() const
3880 return this->GlobalGenerator->GetCMakeInstance();
3883 std::string const& cmLocalGenerator::GetSourceDirectory() const
3885 return this->GetCMakeInstance()->GetHomeDirectory();
3888 std::string const& cmLocalGenerator::GetBinaryDirectory() const
3890 return this->GetCMakeInstance()->GetHomeOutputDirectory();
3893 std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
3895 return this->StateSnapshot.GetDirectory().GetCurrentBinary();
3898 std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
3900 return this->StateSnapshot.GetDirectory().GetCurrentSource();
3903 std::string cmLocalGenerator::GetTargetDirectory(
3904 const cmGeneratorTarget* /*unused*/) const
3906 cmSystemTools::Error("GetTargetDirectory"
3907 " called on cmLocalGenerator");
3911 KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
3913 // The computed version may change until the project is fully
3915 if (!this->BackwardsCompatibilityFinal) {
3916 unsigned int major = 0;
3917 unsigned int minor = 0;
3918 unsigned int patch = 0;
3920 this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
3921 switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
3933 this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
3934 this->BackwardsCompatibilityFinal = true;
3937 return this->BackwardsCompatibility;
3940 bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
3942 // Check the policy to decide whether to pay attention to this
3944 switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
3945 case cmPolicies::WARN:
3946 // WARN is just OLD without warning because user code does not
3947 // always affect whether this check is done.
3949 case cmPolicies::OLD:
3950 // Old behavior is to check the variable.
3952 case cmPolicies::NEW:
3953 // New behavior is to ignore the variable.
3954 case cmPolicies::REQUIRED_IF_USED:
3955 case cmPolicies::REQUIRED_ALWAYS:
3956 // This will never be the case because the only way to require
3957 // the setting is to require the user to specify version policy
3958 // 2.6 or higher. Once we add that requirement then this whole
3959 // method can be removed anyway.
3963 // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
3964 // equal to or lower than the given version.
3965 KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
3966 return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
3969 cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
3970 cmPolicies::PolicyID id) const
3972 return this->Makefile->GetPolicyStatus(id);
3975 bool cmLocalGenerator::CheckDefinition(std::string const& define) const
3977 // Many compilers do not support -DNAME(arg)=sdf so we disable it.
3978 std::string::size_type pos = define.find_first_of("(=");
3979 if (pos != std::string::npos) {
3980 if (define[pos] == '(') {
3981 std::ostringstream e;
3982 /* clang-format off */
3983 e << "WARNING: Function-style preprocessor definitions may not be "
3984 << "passed on the compiler command line because many compilers "
3985 << "do not support it.\n"
3986 << "CMake is dropping a preprocessor definition: " << define << "\n"
3987 << "Consider defining the macro in a (configured) header file.\n";
3988 /* clang-format on */
3989 cmSystemTools::Message(e.str());
3994 // Many compilers do not support # in the value so we disable it.
3995 if (define.find_first_of('#') != std::string::npos) {
3996 std::ostringstream e;
3997 /* clang-format off */
3998 e << "WARNING: Preprocessor definitions containing '#' may not be "
3999 << "passed on the compiler command line because many compilers "
4000 << "do not support it.\n"
4001 << "CMake is dropping a preprocessor definition: " << define << "\n"
4002 << "Consider defining the macro in a (configured) header file.\n";
4003 /* clang-format on */
4004 cmSystemTools::Message(e.str());
4008 // Assume it is supported.
4012 static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
4013 const std::string& prop)
4015 if (cmValue val = target->GetProperty(prop)) {
4016 mf->AddDefinition(prop, *val);
4020 void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
4021 const std::string& targetName,
4022 const std::string& fname)
4024 // Find the Info.plist template.
4025 cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
4026 std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
4027 if (!cmSystemTools::FileIsFullPath(inFile)) {
4028 std::string inMod = this->Makefile->GetModulesFile(inFile);
4029 if (!inMod.empty()) {
4033 if (!cmSystemTools::FileExists(inFile, true)) {
4034 std::ostringstream e;
4035 e << "Target " << target->GetName() << " Info.plist template \"" << inFile
4036 << "\" could not be found.";
4037 cmSystemTools::Error(e.str());
4041 // Convert target properties to variables in an isolated makefile
4042 // scope to configure the file. If properties are set they will
4043 // override user make variables. If not the configuration will fall
4044 // back to the directory-level values set by the user.
4045 cmMakefile* mf = this->Makefile;
4046 cmMakefile::ScopePushPop varScope(mf);
4047 mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
4048 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
4049 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
4050 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
4051 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
4052 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
4053 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
4054 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
4055 cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
4056 mf->ConfigureFile(inFile, fname, false, false, false);
4059 void cmLocalGenerator::GenerateFrameworkInfoPList(
4060 cmGeneratorTarget* target, const std::string& targetName,
4061 const std::string& fname)
4063 // Find the Info.plist template.
4064 cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
4065 std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
4066 if (!cmSystemTools::FileIsFullPath(inFile)) {
4067 std::string inMod = this->Makefile->GetModulesFile(inFile);
4068 if (!inMod.empty()) {
4072 if (!cmSystemTools::FileExists(inFile, true)) {
4073 std::ostringstream e;
4074 e << "Target " << target->GetName() << " Info.plist template \"" << inFile
4075 << "\" could not be found.";
4076 cmSystemTools::Error(e.str());
4080 // Convert target properties to variables in an isolated makefile
4081 // scope to configure the file. If properties are set they will
4082 // override user make variables. If not the configuration will fall
4083 // back to the directory-level values set by the user.
4084 cmMakefile* mf = this->Makefile;
4085 cmMakefile::ScopePushPop varScope(mf);
4086 mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
4087 cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
4088 cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
4089 cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
4090 cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
4091 mf->ConfigureFile(inFile, fname, false, false, false);
4095 cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
4097 return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
4101 void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
4102 cmLocalGenerator::OutputRole role,
4103 cmCommandOrigin origin,
4104 const cmListFileBacktrace& lfbt)
4106 if (cmGeneratorExpression::Find(output) != std::string::npos) {
4107 lg.GetCMakeInstance()->IssueMessage(
4108 MessageType::FATAL_ERROR,
4109 "Generator expressions in custom command outputs are not implemented!",
4114 // Make sure the file will not be generated into the source
4115 // directory during an out of source build.
4116 if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
4117 lg.GetCMakeInstance()->IssueMessage(
4118 MessageType::FATAL_ERROR,
4119 cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
4120 "\nin a source directory as an output of custom command."),
4125 // Make sure the output file name has no invalid characters.
4126 std::string::size_type pos = output.find_first_of("#<>");
4127 if (pos != std::string::npos) {
4128 lg.GetCMakeInstance()->IssueMessage(
4129 MessageType::FATAL_ERROR,
4130 cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
4131 "\" is not allowed."),
4136 // Outputs without generator expressions from the project are already
4137 // created and marked as generated. Do not mark them again, because
4138 // other commands might have overwritten the property.
4139 if (origin == cmCommandOrigin::Generator) {
4140 lg.GetMakefile()->GetOrCreateGeneratedSource(output);
4144 std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
4145 cmListFileBacktrace const& bt,
4146 std::string const& output)
4148 // If the output path has no generator expressions, use it directly.
4149 if (cmGeneratorExpression::Find(output) == std::string::npos) {
4153 // The output path contains a generator expression, but we must choose
4154 // a single source file path to which to attach the custom command.
4155 // Use some heuristics to provide a nice-looking name when possible.
4157 // If the only genex is $<CONFIG>, replace that gracefully.
4159 std::string simple = output;
4160 cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
4161 if (cmGeneratorExpression::Find(simple) == std::string::npos) {
4166 // If the genex evaluates to the same value in all configurations, use that.
4168 std::vector<std::string> allConfigOutputs =
4169 lg.ExpandCustomCommandOutputGenex(output, bt);
4170 if (allConfigOutputs.size() == 1) {
4171 return allConfigOutputs.front();
4175 // Fall back to a deterministic unique name.
4176 cmCryptoHash h(cmCryptoHash::AlgoSHA256);
4177 return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
4178 h.HashString(output).substr(0, 16));
4181 cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
4182 std::unique_ptr<cmCustomCommand> cc,
4185 cmMakefile* mf = lg.GetMakefile();
4186 const auto& lfbt = cc->GetBacktrace();
4187 const auto& outputs = cc->GetOutputs();
4188 const auto& byproducts = cc->GetByproducts();
4189 const auto& commandLines = cc->GetCommandLines();
4191 // Choose a source file on which to store the custom command.
4192 cmSourceFile* file = nullptr;
4193 if (!commandLines.empty() && cc->HasMainDependency()) {
4194 const auto& main_dependency = cc->GetMainDependency();
4195 // The main dependency was specified. Use it unless a different
4196 // custom command already used it.
4197 file = mf->GetSource(main_dependency);
4198 if (file && file->GetCustomCommand() && !replace) {
4199 // The main dependency already has a custom command.
4200 if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
4201 // The existing custom command is identical. Silently ignore
4205 // The existing custom command is different. We need to
4206 // generate a rule file for this new command.
4209 file = mf->CreateSource(main_dependency);
4213 // Generate a rule file if the main dependency is not available.
4215 cmGlobalGenerator* gg = lg.GetGlobalGenerator();
4217 // Construct a rule file associated with the first output produced.
4218 std::string outName = gg->GenerateRuleFile(
4219 ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
4221 // Check if the rule file already exists.
4222 file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
4223 if (file && file->GetCustomCommand() && !replace) {
4224 // The rule file already exists.
4225 if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
4226 lg.GetCMakeInstance()->IssueMessage(
4227 MessageType::FATAL_ERROR,
4228 cmStrCat("Attempt to add a custom rule to output\n ", outName,
4229 "\nwhich already has a custom rule."),
4235 // Create a cmSourceFile for the rule file.
4237 file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
4239 file->SetProperty("__CMAKE_RULE", "1");
4242 // Attach the custom command to the file.
4244 cc->SetEscapeAllowMakeVars(true);
4246 lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
4248 lg.AddSourceOutputs(file, byproducts,
4249 cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
4251 file->SetCustomCommand(std::move(cc));
4256 bool AnyOutputMatches(const std::string& name,
4257 const std::vector<std::string>& outputs)
4259 return std::any_of(outputs.begin(), outputs.end(),
4260 [&name](std::string const& output) -> bool {
4261 std::string::size_type pos = output.rfind(name);
4262 // If the output matches exactly
4263 return (pos != std::string::npos &&
4264 pos == output.size() - name.size() &&
4265 (pos == 0 || output[pos - 1] == '/'));
4269 bool AnyTargetCommandOutputMatches(
4270 const std::string& name, const std::vector<cmCustomCommand>& commands)
4272 return std::any_of(commands.begin(), commands.end(),
4273 [&name](cmCustomCommand const& command) -> bool {
4274 return AnyOutputMatches(name, command.GetByproducts());
4280 void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
4281 cmTarget* target, cmCustomCommandType type,
4282 std::unique_ptr<cmCustomCommand> cc)
4284 // Add the command to the appropriate build step for the target.
4285 cc->SetEscapeAllowMakeVars(true);
4286 cc->SetTarget(target->GetName());
4288 lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
4292 case cmCustomCommandType::PRE_BUILD:
4293 target->AddPreBuildCommand(std::move(*cc));
4295 case cmCustomCommandType::PRE_LINK:
4296 target->AddPreLinkCommand(std::move(*cc));
4298 case cmCustomCommandType::POST_BUILD:
4299 target->AddPostBuildCommand(std::move(*cc));
4306 cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
4307 cmCommandOrigin origin,
4308 std::unique_ptr<cmCustomCommand> cc,
4311 return AddCustomCommand(lg, origin, std::move(cc), replace);
4314 void AppendCustomCommandToOutput(cmLocalGenerator& lg,
4315 const cmListFileBacktrace& lfbt,
4316 const std::string& output,
4317 const std::vector<std::string>& depends,
4318 const cmImplicitDependsList& implicit_depends,
4319 const cmCustomCommandLines& commandLines)
4321 // Lookup an existing command.
4322 cmSourceFile* sf = nullptr;
4323 if (cmGeneratorExpression::Find(output) == std::string::npos) {
4324 sf = lg.GetSourceFileWithOutput(output);
4326 // This output path has a generator expression. Evaluate it to
4327 // find the output for any configurations.
4328 for (std::string const& out :
4329 lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
4330 sf = lg.GetSourceFileWithOutput(out);
4338 if (cmCustomCommand* cc = sf->GetCustomCommand()) {
4339 cc->AppendCommands(commandLines);
4340 cc->AppendDepends(depends);
4341 cc->AppendImplicitDepends(implicit_depends);
4346 // No existing command found.
4347 lg.GetCMakeInstance()->IssueMessage(
4348 MessageType::FATAL_ERROR,
4349 cmStrCat("Attempt to APPEND to custom command with output\n ", output,
4350 "\nwhich is not already a custom command output."),
4354 void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
4355 cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
4357 // They might be moved away
4358 auto byproducts = cc->GetByproducts();
4359 auto lfbt = cc->GetBacktrace();
4361 // Use an empty comment to avoid generation of default comment.
4362 if (!cc->GetComment()) {
4366 // Create the generated symbolic output name of the utility target.
4367 std::string output =
4368 lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
4369 cc->SetOutputs(output);
4371 cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
4374 lg.AddTargetByproducts(target, byproducts, lfbt, origin);
4377 target->AddSource(output);
4380 std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
4382 const std::string& targetProperty =
4383 target->GetSafeProperty("ISPC_INSTRUCTION_SETS");
4384 std::vector<std::string> ispcTargets;
4386 if (!cmIsOff(targetProperty)) {
4387 cmExpandList(targetProperty, ispcTargets);
4388 for (auto& ispcTarget : ispcTargets) {
4389 // transform targets into the suffixes
4390 auto pos = ispcTarget.find('-');
4391 auto target_suffix = ispcTarget.substr(0, pos);
4392 if (target_suffix ==
4393 "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
4394 target_suffix = "avx";
4396 ispcTarget = target_suffix;
4402 std::vector<std::string> ComputeISPCExtraObjects(
4403 std::string const& objectName, std::string const& buildDirectory,
4404 std::vector<std::string> const& ispcSuffixes)
4406 auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
4407 std::vector<std::string> computedObjects;
4408 computedObjects.reserve(ispcSuffixes.size());
4410 auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
4412 // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
4413 // drops any directories in objectName
4414 auto objNameNoExt = objectName;
4415 std::string::size_type dot_pos = objectName.rfind('.');
4416 if (dot_pos != std::string::npos) {
4417 objNameNoExt.resize(dot_pos);
4420 for (const auto& ispcTarget : ispcSuffixes) {
4421 computedObjects.emplace_back(
4422 cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
4425 return computedObjects;
4429 cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
4430 const std::string& name) const
4432 // Linear search? Also see GetSourceFileWithOutput for detail.
4433 if (!cmSystemTools::FileIsFullPath(name)) {
4434 cmSourcesWithOutput sources;
4435 sources.Target = this->LinearGetTargetWithOutput(name);
4436 sources.Source = this->LinearGetSourceFileWithOutput(
4437 name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
4440 // Otherwise we use an efficient lookup map.
4441 auto o = this->OutputToSource.find(name);
4442 if (o != this->OutputToSource.end()) {
4443 return o->second.Sources;
4448 cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
4449 const std::string& name, cmSourceOutputKind kind) const
4451 // If the queried path is not absolute we use the backward compatible
4452 // linear-time search for an output with a matching suffix.
4453 if (!cmSystemTools::FileIsFullPath(name)) {
4454 bool byproduct = false;
4455 return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
4457 // Otherwise we use an efficient lookup map.
4458 auto o = this->OutputToSource.find(name);
4459 if (o != this->OutputToSource.end() &&
4460 (!o->second.Sources.SourceIsByproduct ||
4461 kind == cmSourceOutputKind::OutputOrByproduct)) {
4462 // Source file could also be null pointer for example if we found the
4463 // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
4464 // command of a target, or a not yet created custom command.
4465 return o->second.Sources.Source;
4470 std::string cmLocalGenerator::CreateUtilityOutput(
4471 std::string const& targetName, std::vector<std::string> const&,
4472 cmListFileBacktrace const&)
4475 cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
4476 // The output is not actually created so mark it symbolic.
4477 if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
4478 sf->SetProperty("SYMBOLIC", "1");
4480 cmSystemTools::Error("Could not get source file entry for " + force);
4485 std::vector<cmCustomCommandGenerator>
4486 cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
4487 std::string const& config)
4489 std::vector<cmCustomCommandGenerator> ccgs;
4490 ccgs.emplace_back(cc, config, this);
4494 std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
4495 cmCompiledGeneratorExpression const& cge, std::string const& config)
4497 std::vector<std::string> paths = cmExpandedList(cge.Evaluate(this, config));
4498 for (std::string& p : paths) {
4499 p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
4504 std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
4505 std::string const& o, cmListFileBacktrace const& bt)
4507 std::vector<std::string> allConfigOutputs;
4508 cmGeneratorExpression ge(bt);
4509 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
4510 std::vector<std::string> configs =
4511 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
4512 for (std::string const& config : configs) {
4513 std::vector<std::string> configOutputs =
4514 this->ExpandCustomCommandOutputPaths(*cge, config);
4515 allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
4516 std::move(configOutputs.begin(), configOutputs.end(),
4517 std::back_inserter(allConfigOutputs));
4520 cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
4521 allConfigOutputs.erase(endUnique, allConfigOutputs.end());
4522 return allConfigOutputs;
4525 void cmLocalGenerator::AddTargetByproducts(
4526 cmTarget* target, const std::vector<std::string>& byproducts,
4527 cmListFileBacktrace const& bt, cmCommandOrigin origin)
4529 for (std::string const& o : byproducts) {
4530 if (cmGeneratorExpression::Find(o) == std::string::npos) {
4531 this->UpdateOutputToSourceMap(o, target, bt, origin);
4535 // This byproduct path has a generator expression. Evaluate it to
4536 // register the byproducts for all configurations.
4537 for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
4538 this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
4543 void cmLocalGenerator::AddSourceOutputs(
4544 cmSourceFile* source, const std::vector<std::string>& outputs,
4545 OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
4547 for (std::string const& o : outputs) {
4548 if (cmGeneratorExpression::Find(o) == std::string::npos) {
4549 this->UpdateOutputToSourceMap(o, source, role, bt, origin);
4553 // This output path has a generator expression. Evaluate it to
4554 // register the outputs for all configurations.
4555 for (std::string const& out :
4556 this->ExpandCustomCommandOutputGenex(o, bt)) {
4557 this->UpdateOutputToSourceMap(out, source, role, bt,
4558 cmCommandOrigin::Generator);
4563 void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
4565 cmListFileBacktrace const& bt,
4566 cmCommandOrigin origin)
4569 entry.Sources.Target = target;
4571 auto pr = this->OutputToSource.emplace(byproduct, entry);
4573 CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
4575 SourceEntry& current = pr.first->second;
4576 // Has the target already been set?
4577 if (!current.Sources.Target) {
4578 current.Sources.Target = target;
4580 // Multiple custom commands/targets produce the same output (source file
4581 // or target). See also comment in other UpdateOutputToSourceMap
4584 // TODO: Warn the user about this case.
4589 void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
4590 cmSourceFile* source,
4592 cmListFileBacktrace const& bt,
4593 cmCommandOrigin origin)
4596 entry.Sources.Source = source;
4597 entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
4599 auto pr = this->OutputToSource.emplace(output, entry);
4601 CreateGeneratedSource(*this, output, role, origin, bt);
4603 SourceEntry& current = pr.first->second;
4604 // Outputs take precedence over byproducts
4605 if (!current.Sources.Source ||
4606 (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
4607 current.Sources.Source = source;
4608 current.Sources.SourceIsByproduct = false;
4610 // Multiple custom commands produce the same output but may
4611 // be attached to a different source file (MAIN_DEPENDENCY).
4612 // LinearGetSourceFileWithOutput would return the first one,
4613 // so keep the mapping for the first one.
4615 // TODO: Warn the user about this case. However, the VS 8 generator
4616 // triggers it for separate generate.stamp rules in ZERO_CHECK and
4617 // individual targets.
4622 cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
4623 const std::string& name) const
4625 // We go through the ordered vector of targets to get reproducible results
4626 // should multiple names match.
4627 for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
4628 // Does the output of any command match the source file name?
4629 if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
4632 if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
4635 if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
4642 cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
4643 const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
4645 // Outputs take precedence over byproducts.
4647 cmSourceFile* fallback = nullptr;
4649 // Look through all the source files that have custom commands and see if the
4650 // custom command has the passed source file as an output.
4651 for (const auto& src : this->Makefile->GetSourceFiles()) {
4652 // Does this source file have a custom command?
4653 if (src->GetCustomCommand()) {
4654 // Does the output of the custom command match the source file name?
4655 if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
4656 // Return the first matching output.
4659 if (kind == cmSourceOutputKind::OutputOrByproduct) {
4660 if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
4661 // Do not return the source yet as there might be a matching output.
4662 fallback = src.get();
4668 // Did we find a byproduct?
4669 byproduct = fallback != nullptr;