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 "cmGlobalXCodeGenerator.h"
12 #include <unordered_set>
16 #include <cmext/algorithm>
17 #include <cmext/string_view>
19 #include "cmsys/RegularExpression.hxx"
21 #include "cmComputeLinkInformation.h"
22 #include "cmCryptoHash.h"
23 #include "cmCustomCommand.h"
24 #include "cmCustomCommandGenerator.h"
25 #include "cmCustomCommandLines.h"
26 #include "cmCustomCommandTypes.h"
27 #include "cmDocumentationEntry.h"
28 #include "cmGeneratedFileStream.h"
29 #include "cmGeneratorExpression.h"
30 #include "cmGeneratorTarget.h"
31 #include "cmGlobalGeneratorFactory.h"
32 #include "cmLinkItem.h"
33 #include "cmListFileCache.h"
34 #include "cmLocalGenerator.h"
35 #include "cmLocalXCodeGenerator.h"
36 #include "cmMakefile.h"
37 #include "cmMessageType.h"
38 #include "cmOutputConverter.h"
39 #include "cmPolicies.h"
40 #include "cmSourceFile.h"
41 #include "cmSourceFileLocation.h"
42 #include "cmSourceFileLocationKind.h"
43 #include "cmSourceGroup.h"
45 #include "cmStateSnapshot.h"
46 #include "cmStateTypes.h"
47 #include "cmStringAlgorithms.h"
48 #include "cmSystemTools.h"
50 #include "cmTargetDepend.h"
51 #include "cmXCode21Object.h"
52 #include "cmXCodeObject.h"
53 #include "cmXCodeScheme.h"
54 #include "cmXMLWriter.h"
57 #if !defined(CMAKE_BOOTSTRAP) && defined(__APPLE__)
58 # include <CoreFoundation/CoreFoundation.h>
59 # if !TARGET_OS_IPHONE
60 # define HAVE_APPLICATION_SERVICES
61 # include <ApplicationServices/ApplicationServices.h>
65 #if !defined(CMAKE_BOOTSTRAP)
66 # include "cmXMLParser.h"
68 // parse the xml file storing the installed version of Xcode on
70 class cmXcodeVersionParser : public cmXMLParser
73 cmXcodeVersionParser()
77 void StartElement(const std::string&, const char**) override
81 void EndElement(const std::string& name) override
84 this->Key = this->Data;
85 } else if (name == "string") {
86 if (this->Key == "CFBundleShortVersionString") {
87 this->Version = this->Data;
91 void CharacterDataHandler(const char* data, int length) override
93 this->Data.append(data, length);
101 // Builds either an object list or a space-separated string from the
103 class cmGlobalXCodeGenerator::BuildObjectListOrString
105 cmGlobalXCodeGenerator* Generator;
106 cmXCodeObject* Group;
111 BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList)
116 if (buildObjectList) {
117 this->Group = this->Generator->CreateObject(cmXCodeObject::OBJECT_LIST);
121 bool IsEmpty() const { return this->Empty; }
123 void Add(const std::string& newString)
128 this->Group->AddObject(this->Generator->CreateString(newString));
130 this->String += newString;
135 const std::string& GetString() const { return this->String; }
137 cmXCodeObject* CreateList()
142 return this->Generator->CreateString(this->String);
146 class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
149 std::unique_ptr<cmGlobalGenerator> CreateGlobalGenerator(
150 const std::string& name, bool allowArch, cmake* cm) const override;
152 void GetDocumentation(cmDocumentationEntry& entry) const override
154 cmGlobalXCodeGenerator::GetDocumentation(entry);
157 std::vector<std::string> GetGeneratorNames() const override
159 std::vector<std::string> names;
160 names.push_back(cmGlobalXCodeGenerator::GetActualName());
164 std::vector<std::string> GetGeneratorNamesWithPlatform() const override
166 return std::vector<std::string>();
169 bool SupportsToolset() const override { return true; }
170 bool SupportsPlatform() const override { return false; }
172 std::vector<std::string> GetKnownPlatforms() const override
174 return std::vector<std::string>();
177 std::string GetDefaultPlatformName() const override { return std::string(); }
180 cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
181 cmake* cm, std::string const& version_string, unsigned int version_number)
182 : cmGlobalGenerator(cm)
184 this->VersionString = version_string;
185 this->XcodeVersion = version_number;
186 if (this->XcodeVersion >= 120) {
187 this->XcodeBuildSystem = BuildSystem::Twelve;
189 this->XcodeBuildSystem = BuildSystem::One;
192 this->RootObject = nullptr;
193 this->MainGroupChildren = nullptr;
194 this->FrameworkGroup = nullptr;
195 this->CurrentMakefile = nullptr;
196 this->CurrentLocalGenerator = nullptr;
197 this->XcodeBuildCommandInitialized = false;
199 this->ObjectDirArchDefault = "$(CURRENT_ARCH)";
200 this->ObjectDirArch = this->ObjectDirArchDefault;
202 cm->GetState()->SetIsGeneratorMultiConfig(true);
205 std::unique_ptr<cmGlobalGeneratorFactory> cmGlobalXCodeGenerator::NewFactory()
207 return std::unique_ptr<cmGlobalGeneratorFactory>(new Factory);
210 std::unique_ptr<cmGlobalGenerator>
211 cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(const std::string& name,
215 if (name != GetActualName()) {
216 return std::unique_ptr<cmGlobalGenerator>();
218 #if !defined(CMAKE_BOOTSTRAP)
219 cmXcodeVersionParser parser;
220 std::string versionFile;
223 bool commandResult = cmSystemTools::RunSingleCommand(
224 "xcode-select --print-path", &out, nullptr, nullptr, nullptr,
225 cmSystemTools::OUTPUT_NONE);
227 std::string::size_type pos = out.find(".app/");
228 if (pos != std::string::npos) {
229 versionFile = out.substr(0, pos + 5) + "Contents/version.plist";
233 if (!versionFile.empty() && cmSystemTools::FileExists(versionFile)) {
234 parser.ParseFile(versionFile.c_str());
235 } else if (cmSystemTools::FileExists(
236 "/Applications/Xcode.app/Contents/version.plist")) {
237 parser.ParseFile("/Applications/Xcode.app/Contents/version.plist");
240 "/Developer/Applications/Xcode.app/Contents/version.plist");
242 std::string const& version_string = parser.Version;
244 // Compute an integer form of the version number.
245 unsigned int v[2] = { 0, 0 };
246 sscanf(version_string.c_str(), "%u.%u", &v[0], &v[1]);
247 unsigned int version_number = 10 * v[0] + v[1];
249 if (version_number < 50) {
250 cm->IssueMessage(MessageType::FATAL_ERROR,
251 "Xcode " + version_string + " not supported.");
252 return std::unique_ptr<cmGlobalGenerator>();
255 return std::unique_ptr<cmGlobalGenerator>(
256 cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string,
259 std::cerr << "CMake should be built with cmake to use Xcode, "
260 "default to Xcode 1.5\n";
261 return std::unique_ptr<cmGlobalGenerator>(
262 cm::make_unique<cmGlobalXCodeGenerator>(cm));
266 bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
268 // The Xcode generator knows how to lookup its build tool
269 // directly instead of needing a helper module to do it, so we
270 // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
271 if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
272 mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetXcodeBuildCommand());
277 std::string const& cmGlobalXCodeGenerator::GetXcodeBuildCommand()
279 if (!this->XcodeBuildCommandInitialized) {
280 this->XcodeBuildCommandInitialized = true;
281 this->XcodeBuildCommand = this->FindXcodeBuildCommand();
283 return this->XcodeBuildCommand;
286 std::string cmGlobalXCodeGenerator::FindXcodeBuildCommand()
288 std::string makeProgram = cmSystemTools::FindProgram("xcodebuild");
289 if (makeProgram.empty()) {
290 makeProgram = "xcodebuild";
295 bool cmGlobalXCodeGenerator::SetSystemName(std::string const& s,
298 this->SystemName = s;
299 return this->cmGlobalGenerator::SetSystemName(s, mf);
303 cm::string_view cmXcodeBuildSystemString(cmGlobalXCodeGenerator::BuildSystem b)
306 case cmGlobalXCodeGenerator::BuildSystem::One:
308 case cmGlobalXCodeGenerator::BuildSystem::Twelve:
315 bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
316 bool build, cmMakefile* mf)
318 if (!this->ParseGeneratorToolset(ts, mf)) {
324 if (!this->GeneratorToolset.empty()) {
325 mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET", this->GeneratorToolset);
327 mf->AddDefinition("CMAKE_XCODE_BUILD_SYSTEM",
328 cmXcodeBuildSystemString(this->XcodeBuildSystem));
332 bool cmGlobalXCodeGenerator::ParseGeneratorToolset(std::string const& ts,
335 std::vector<std::string> const fields = cmTokenize(ts, ",");
336 auto fi = fields.cbegin();
337 if (fi == fields.cend()) {
341 // The first field may be the Xcode GCC_VERSION.
342 if (fi->find('=') == fi->npos) {
343 this->GeneratorToolset = *fi;
347 std::unordered_set<std::string> handled;
349 // The rest of the fields must be key=value pairs.
350 for (; fi != fields.cend(); ++fi) {
351 std::string::size_type pos = fi->find('=');
352 if (pos == fi->npos) {
353 /* clang-format off */
354 std::string const& e = cmStrCat(
356 " ", this->GetName(), "\n"
357 "given toolset specification\n"
359 "that contains a field after the first ',' with no '='."
361 /* clang-format on */
362 mf->IssueMessage(MessageType::FATAL_ERROR, e);
365 std::string const key = fi->substr(0, pos);
366 std::string const value = fi->substr(pos + 1);
367 if (!handled.insert(key).second) {
368 /* clang-format off */
369 std::string const& e = cmStrCat(
371 " ", this->GetName(), "\n"
372 "given toolset specification\n"
374 "that contains duplicate field key '", key, "'."
376 /* clang-format on */
377 mf->IssueMessage(MessageType::FATAL_ERROR, e);
380 if (!this->ProcessGeneratorToolsetField(key, value, mf)) {
388 bool cmGlobalXCodeGenerator::ProcessGeneratorToolsetField(
389 std::string const& key, std::string const& value, cmMakefile* mf)
391 if (key == "buildsystem") {
392 if (value == "1"_s) {
393 this->XcodeBuildSystem = BuildSystem::One;
394 } else if (value == "12"_s) {
395 this->XcodeBuildSystem = BuildSystem::Twelve;
397 /* clang-format off */
398 std::string const& e = cmStrCat(
400 " ", this->GetName(), "\n"
401 "toolset specification field\n"
402 " buildsystem=", value, "\n"
403 "value is unknown. It must be '1' or '12'."
405 /* clang-format on */
406 mf->IssueMessage(MessageType::FATAL_ERROR, e);
409 if (this->XcodeBuildSystem == BuildSystem::Twelve &&
410 this->XcodeVersion < 120) {
411 /* clang-format off */
412 std::string const& e = cmStrCat(
414 " ", this->GetName(), "\n"
415 "toolset specification field\n"
416 " buildsystem=", value, "\n"
417 "is not allowed with Xcode ", this->VersionString, '.'
419 /* clang-format on */
420 mf->IssueMessage(MessageType::FATAL_ERROR, e);
425 /* clang-format off */
426 std::string const& e = cmStrCat(
428 " ", this->GetName(), "\n"
429 "given toolset specification that contains invalid field '", key, "'."
431 /* clang-format on */
432 mf->IssueMessage(MessageType::FATAL_ERROR, e);
436 void cmGlobalXCodeGenerator::EnableLanguage(
437 std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
439 mf->AddDefinition("XCODE", "1");
440 mf->AddDefinition("XCODE_VERSION", this->VersionString);
441 mf->InitCMAKE_CONFIGURATION_TYPES("Debug;Release;MinSizeRel;RelWithDebInfo");
442 mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
443 this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
444 this->ComputeArchitectures(mf);
447 bool cmGlobalXCodeGenerator::Open(const std::string& bindir,
448 const std::string& projectName, bool dryRun)
452 #ifdef HAVE_APPLICATION_SERVICES
453 std::string url = bindir + "/" + projectName + ".xcodeproj";
456 return cmSystemTools::FileExists(url, false);
459 CFStringRef cfStr = CFStringCreateWithCString(
460 kCFAllocatorDefault, url.c_str(), kCFStringEncodingUTF8);
462 CFURLRef cfUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfStr,
463 kCFURLPOSIXPathStyle, true);
465 OSStatus err = LSOpenCFURLRef(cfUrl, nullptr);
480 std::vector<cmGlobalGenerator::GeneratedMakeCommand>
481 cmGlobalXCodeGenerator::GenerateBuildCommand(
482 const std::string& makeProgram, const std::string& projectName,
483 const std::string& /*projectDir*/,
484 std::vector<std::string> const& targetNames, const std::string& config,
485 int jobs, bool /*verbose*/, const cmBuildOptions& /*buildOptions*/,
486 std::vector<std::string> const& makeOptions)
488 GeneratedMakeCommand makeCommand;
489 // now build the test
491 this->SelectMakeProgram(makeProgram, this->GetXcodeBuildCommand()));
493 if (!projectName.empty()) {
494 makeCommand.Add("-project");
495 std::string projectArg = cmStrCat(projectName, ".xcodeproj");
496 makeCommand.Add(projectArg);
498 if (cm::contains(targetNames, "clean")) {
499 makeCommand.Add("clean");
500 makeCommand.Add("-target", "ALL_BUILD");
502 makeCommand.Add("build");
503 if (targetNames.empty() ||
504 ((targetNames.size() == 1) && targetNames.front().empty())) {
505 makeCommand.Add("-target", "ALL_BUILD");
507 for (const auto& tname : targetNames) {
508 if (!tname.empty()) {
509 makeCommand.Add("-target", tname);
515 if ((this->XcodeBuildSystem >= BuildSystem::Twelve) ||
516 (jobs != cmake::NO_BUILD_PARALLEL_LEVEL)) {
517 makeCommand.Add("-parallelizeTargets");
519 makeCommand.Add("-configuration", (config.empty() ? "Debug" : config));
521 if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
522 (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
523 makeCommand.Add("-jobs", std::to_string(jobs));
526 if (this->XcodeVersion >= 70) {
527 makeCommand.Add("-hideShellScriptEnvironment");
529 makeCommand.Add(makeOptions.begin(), makeOptions.end());
530 return { std::move(makeCommand) };
533 //! Create a local generator appropriate to this Global Generator
534 std::unique_ptr<cmLocalGenerator> cmGlobalXCodeGenerator::CreateLocalGenerator(
537 std::unique_ptr<cmLocalGenerator> lg(
538 cm::make_unique<cmLocalXCodeGenerator>(this, mf));
539 if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
540 // For this build system variant we generate custom commands as
541 // shell scripts directly rather than inside Makefiles.
542 // FIXME: Rename or refactor this option for clarity.
543 lg->SetLinkScriptShell(true);
548 void cmGlobalXCodeGenerator::AddExtraIDETargets()
550 // make sure extra targets are added before calling
551 // the parent generate which will call trace depends
552 for (auto keyVal : this->ProjectMap) {
553 cmLocalGenerator* root = keyVal.second[0];
554 this->SetGenerationRoot(root);
555 // add ALL_BUILD, INSTALL, etc
556 this->AddExtraTargets(root, keyVal.second);
560 void cmGlobalXCodeGenerator::Generate()
562 this->cmGlobalGenerator::Generate();
563 if (cmSystemTools::GetErrorOccurredFlag()) {
567 for (auto keyVal : this->ProjectMap) {
568 cmLocalGenerator* root = keyVal.second[0];
570 bool generateTopLevelProjectOnly =
571 root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
573 if (generateTopLevelProjectOnly) {
574 cmStateSnapshot snp = root->GetStateSnapshot();
575 if (snp.GetBuildsystemDirectoryParent().IsValid()) {
580 // cache the enabled languages for source file type queries
581 this->GetEnabledLanguages(this->EnabledLangs);
583 this->SetGenerationRoot(root);
584 // now create the project
585 this->OutputXCodeProject(root, keyVal.second);
589 void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root)
591 this->CurrentProject = root->GetProjectName();
592 this->SetCurrentLocalGenerator(root);
593 this->CurrentRootGenerator = root;
594 this->CurrentXCodeHackMakefile =
595 cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
596 cmSystemTools::MakeDirectory(this->CurrentXCodeHackMakefile);
597 this->CurrentXCodeHackMakefile += "/XCODE_DEPEND_HELPER.make";
600 std::string cmGlobalXCodeGenerator::PostBuildMakeTarget(
601 std::string const& tName, std::string const& configName)
603 std::string target = tName;
604 std::replace(target.begin(), target.end(), ' ', '_');
605 std::string out = cmStrCat("PostBuild.", target, '.', configName);
609 #define CMAKE_CHECK_BUILD_SYSTEM_TARGET "ZERO_CHECK"
611 void cmGlobalXCodeGenerator::AddExtraTargets(
612 cmLocalGenerator* root, std::vector<cmLocalGenerator*>& gens)
615 auto cc = cm::make_unique<cmCustomCommand>();
617 cmMakeSingleCommandLine({ "echo", "Build all projects" }));
618 cc->SetCMP0116Status(cmPolicies::NEW);
620 root->AddUtilityCommand("ALL_BUILD", true, std::move(cc));
622 // Add xcconfig files to ALL_BUILD sources
623 for (auto& config : this->CurrentConfigurationTypes) {
624 auto xcconfig = cmGeneratorExpression::Evaluate(
625 this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
626 this->CurrentLocalGenerator, config);
627 if (!xcconfig.empty()) {
628 allbuild->AddSource(xcconfig);
632 root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(allbuild, root));
634 // Add XCODE depend helper
635 std::string legacyDependHelperDir = root->GetCurrentBinaryDirectory();
636 cmCustomCommandLines legacyDependHelperCommandLines;
637 if (this->XcodeBuildSystem == BuildSystem::One) {
638 legacyDependHelperCommandLines = cmMakeSingleCommandLine(
639 { "make", "-C", legacyDependHelperDir, "-f",
640 this->CurrentXCodeHackMakefile, "OBJDIR=$(OBJDIR)",
641 /* placeholder, see below */ "" });
645 bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
646 bool generateTopLevelProjectOnly =
647 root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
649 !root->GetStateSnapshot().GetBuildsystemDirectoryParent().IsValid();
650 bool isGenerateProject = isTopLevel || !generateTopLevelProjectOnly;
651 if (regenerate && isGenerateProject) {
652 this->CreateReRunCMakeFile(root, gens);
654 this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile);
655 cmSystemTools::ReplaceString(file, "\\ ", " ");
656 cc = cm::make_unique<cmCustomCommand>();
657 cc->SetCommandLines(cmMakeSingleCommandLine({ "make", "-f", file }));
658 cc->SetCMP0116Status(cmPolicies::NEW);
659 cmTarget* check = root->AddUtilityCommand(CMAKE_CHECK_BUILD_SYSTEM_TARGET,
660 true, std::move(cc));
662 root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(check, root));
665 // now make the allbuild depend on all the non-utility targets
667 for (auto& gen : gens) {
668 for (const auto& target : gen->GetGeneratorTargets()) {
669 if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
674 (target->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET)) {
675 target->Target->AddUtility(CMAKE_CHECK_BUILD_SYSTEM_TARGET, false);
678 // make all exe, shared libs and modules
679 // run the depend check makefile as a post build rule
680 // this will make sure that when the next target is built
681 // things are up-to-date
682 if (this->XcodeBuildSystem == BuildSystem::One && isGenerateProject &&
683 target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
684 legacyDependHelperCommandLines.front().back() = // fill placeholder
685 this->PostBuildMakeTarget(target->GetName(), "$(CONFIGURATION)");
686 cc = cm::make_unique<cmCustomCommand>();
687 cc->SetCommandLines(legacyDependHelperCommandLines);
688 cc->SetComment("Depend check for xcode");
689 cc->SetWorkingDirectory(legacyDependHelperDir.c_str());
690 cc->SetCMP0116Status(cmPolicies::NEW);
691 gen->AddCustomCommandToTarget(
692 target->GetName(), cmCustomCommandType::POST_BUILD, std::move(cc),
693 cmObjectLibraryCommands::Accept);
696 if (!this->IsExcluded(gens[0], target.get())) {
697 allbuild->AddUtility(target->GetName(), false);
703 void cmGlobalXCodeGenerator::CreateReRunCMakeFile(
704 cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens)
706 std::vector<std::string> lfiles;
707 for (auto gen : gens) {
708 cm::append(lfiles, gen->GetMakefile()->GetListFiles());
712 std::sort(lfiles.begin(), lfiles.end());
713 lfiles.erase(std::unique(lfiles.begin(), lfiles.end()), lfiles.end());
715 cmake* cm = this->GetCMakeInstance();
716 if (cm->DoWriteGlobVerifyTarget()) {
717 lfiles.emplace_back(cm->GetGlobVerifyStamp());
720 this->CurrentReRunCMakeMakefile =
721 cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
722 cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile);
723 this->CurrentReRunCMakeMakefile += "/ReRunCMake.make";
724 cmGeneratedFileStream makefileStream(this->CurrentReRunCMakeMakefile);
725 makefileStream.SetCopyIfDifferent(true);
726 makefileStream << "# Generated by CMake, DO NOT EDIT\n\n";
728 makefileStream << "TARGETS:= \n";
729 makefileStream << "empty:= \n";
730 makefileStream << "space:= $(empty) $(empty)\n";
731 makefileStream << "spaceplus:= $(empty)\\ $(empty)\n\n";
733 for (const auto& lfile : lfiles) {
734 makefileStream << "TARGETS += $(subst $(space),$(spaceplus),$(wildcard "
735 << this->ConvertToRelativeForMake(lfile) << "))\n";
737 makefileStream << "\n";
739 std::string checkCache =
740 cmStrCat(root->GetBinaryDirectory(), "/CMakeFiles/cmake.check_cache");
742 if (cm->DoWriteGlobVerifyTarget()) {
743 makefileStream << ".NOTPARALLEL:\n\n";
744 makefileStream << ".PHONY: all VERIFY_GLOBS\n\n";
745 makefileStream << "all: VERIFY_GLOBS "
746 << this->ConvertToRelativeForMake(checkCache) << "\n\n";
747 makefileStream << "VERIFY_GLOBS:\n";
748 makefileStream << "\t"
749 << this->ConvertToRelativeForMake(
750 cmSystemTools::GetCMakeCommand())
752 << this->ConvertToRelativeForMake(cm->GetGlobVerifyScript())
756 makefileStream << this->ConvertToRelativeForMake(checkCache)
758 makefileStream << "\t"
759 << this->ConvertToRelativeForMake(
760 cmSystemTools::GetCMakeCommand())
762 << this->ConvertToRelativeForMake(root->GetSourceDirectory())
764 << this->ConvertToRelativeForMake(root->GetBinaryDirectory())
768 static bool objectIdLessThan(const std::unique_ptr<cmXCodeObject>& l,
769 const std::unique_ptr<cmXCodeObject>& r)
771 return l->GetId() < r->GetId();
774 void cmGlobalXCodeGenerator::SortXCodeObjects()
776 std::sort(this->XCodeObjects.begin(), this->XCodeObjects.end(),
780 void cmGlobalXCodeGenerator::ClearXCodeObjects()
782 this->TargetDoneSet.clear();
783 this->XCodeObjects.clear();
784 this->XCodeObjectIDs.clear();
785 this->XCodeObjectMap.clear();
786 this->GroupMap.clear();
787 this->GroupNameMap.clear();
788 this->TargetGroup.clear();
789 this->FileRefs.clear();
790 this->ExternalLibRefs.clear();
791 this->EmbeddedLibRefs.clear();
792 this->FileRefToBuildFileMap.clear();
793 this->FileRefToEmbedBuildFileMap.clear();
794 this->CommandsVisited.clear();
797 void cmGlobalXCodeGenerator::addObject(std::unique_ptr<cmXCodeObject> obj)
799 if (obj->GetType() == cmXCodeObject::OBJECT) {
800 const std::string& id = obj->GetId();
802 // If this is a duplicate id, it's an error:
804 if (this->XCodeObjectIDs.count(id)) {
805 cmSystemTools::Error(
806 "Xcode generator: duplicate object ids not allowed");
809 this->XCodeObjectIDs.insert(id);
812 this->XCodeObjects.push_back(std::move(obj));
815 cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(
816 cmXCodeObject::PBXType ptype, cm::string_view key)
818 auto obj = cm::make_unique<cmXCode21Object>(ptype, cmXCodeObject::OBJECT,
819 this->GetObjectId(ptype, key));
820 auto ptr = obj.get();
821 this->addObject(std::move(obj));
825 cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::Type type)
827 auto obj = cm::make_unique<cmXCodeObject>(
828 cmXCodeObject::None, type,
829 "Temporary cmake object, should not be referred to in Xcode file");
830 auto ptr = obj.get();
831 this->addObject(std::move(obj));
835 cmXCodeObject* cmGlobalXCodeGenerator::CreateString(const std::string& s)
837 cmXCodeObject* obj = this->CreateObject(cmXCodeObject::STRING);
842 cmXCodeObject* cmGlobalXCodeGenerator::CreateObjectReference(
845 cmXCodeObject* obj = this->CreateObject(cmXCodeObject::OBJECT_REF);
850 cmXCodeObject* cmGlobalXCodeGenerator::CreateFlatClone(cmXCodeObject* orig)
852 cmXCodeObject* obj = this->CreateObject(orig->GetType());
853 obj->CopyAttributes(orig);
857 static std::string GetGroupMapKeyFromPath(cmGeneratorTarget* target,
858 const std::string& fullpath)
860 std::string key(target->GetName());
866 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeBuildFileFromPath(
867 const std::string& fullpath, cmGeneratorTarget* target,
868 const std::string& lang, cmSourceFile* sf)
870 // Using a map and the full path guarantees that we will always get the same
871 // fileRef object for any given full path. Same goes for the buildFile
873 cmXCodeObject* fileRef =
874 this->CreateXCodeFileReferenceFromPath(fullpath, target, lang, sf);
876 auto it = this->FileRefToBuildFileMap.find(fileRef);
877 if (it == this->FileRefToBuildFileMap.end()) {
878 cmXCodeObject* buildFile =
879 this->CreateObject(cmXCodeObject::PBXBuildFile);
880 buildFile->SetComment(fileRef->GetComment());
881 buildFile->AddAttribute("fileRef", this->CreateObjectReference(fileRef));
882 this->FileRefToBuildFileMap[fileRef] = buildFile;
890 class XCodeGeneratorExpressionInterpreter
891 : public cmGeneratorExpressionInterpreter
894 XCodeGeneratorExpressionInterpreter(cmSourceFile* sourceFile,
895 cmLocalGenerator* localGenerator,
896 cmGeneratorTarget* headTarget,
897 const std::string& lang)
898 : cmGeneratorExpressionInterpreter(
899 localGenerator, "NO-PER-CONFIG-SUPPORT-IN-XCODE", headTarget, lang)
900 , SourceFile(sourceFile)
904 XCodeGeneratorExpressionInterpreter(
905 XCodeGeneratorExpressionInterpreter const&) = delete;
906 XCodeGeneratorExpressionInterpreter& operator=(
907 XCodeGeneratorExpressionInterpreter const&) = delete;
909 const std::string& Evaluate(const char* expression,
910 const std::string& property)
912 return this->Evaluate(std::string(expression ? expression : ""), property);
915 const std::string& Evaluate(const std::string& expression,
916 const std::string& property)
918 const std::string& processed =
919 this->cmGeneratorExpressionInterpreter::Evaluate(expression, property);
920 if (this->CompiledGeneratorExpression->GetHadContextSensitiveCondition()) {
921 std::ostringstream e;
922 /* clang-format off */
924 "Xcode does not support per-config per-source " << property << ":\n"
925 " " << expression << "\n"
926 "specified for source:\n"
927 " " << this->SourceFile->ResolveFullPath() << "\n";
928 /* clang-format on */
929 this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
936 cmSourceFile* SourceFile = nullptr;
939 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
940 cmLocalGenerator* lg, cmSourceFile* sf, cmGeneratorTarget* gtgt)
942 std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
944 XCodeGeneratorExpressionInterpreter genexInterpreter(sf, lg, gtgt, lang);
946 // Add flags from target and source file properties.
948 std::string const& srcfmt = sf->GetSafeProperty("Fortran_FORMAT");
949 switch (cmOutputConverter::GetFortranFormat(srcfmt)) {
950 case cmOutputConverter::FortranFormatFixed:
951 flags = "-fixed " + flags;
953 case cmOutputConverter::FortranFormatFree:
954 flags = "-free " + flags;
960 // Explicitly add the explicit language flag before any other flag
961 // so user flags can override it.
962 gtgt->AddExplicitLanguageFlags(flags, *sf);
964 const std::string COMPILE_FLAGS("COMPILE_FLAGS");
965 if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
966 lg->AppendFlags(flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
968 const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
969 if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
970 lg->AppendCompileOptions(
971 flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
974 // Add per-source definitions.
975 BuildObjectListOrString flagsBuild(this, false);
976 const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
977 if (cmValue compile_defs = sf->GetProperty(COMPILE_DEFINITIONS)) {
980 genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS).c_str(),
984 if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
985 this->AppendDefines(flagsBuild, "CMAKE_SKIP_PRECOMPILE_HEADERS", true);
988 if (!flagsBuild.IsEmpty()) {
989 if (!flags.empty()) {
992 flags += flagsBuild.GetString();
995 // Add per-source include directories.
996 std::vector<std::string> includes;
997 const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
998 if (cmValue cincludes = sf->GetProperty(INCLUDE_DIRECTORIES)) {
999 lg->AppendIncludeDirectories(
1000 includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
1003 lg->AppendFlags(flags,
1004 lg->GetIncludeFlags(includes, gtgt, lang, std::string()));
1006 cmXCodeObject* buildFile =
1007 this->CreateXCodeBuildFileFromPath(sf->ResolveFullPath(), gtgt, lang, sf);
1009 cmXCodeObject* settings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
1010 settings->AddAttributeIfNotEmpty("COMPILER_FLAGS",
1011 this->CreateString(flags));
1013 cmGeneratorTarget::SourceFileFlags tsFlags =
1014 gtgt->GetTargetSourceFileFlags(sf);
1016 cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1018 // Is this a "private" or "public" framework header file?
1019 // Set the ATTRIBUTES attribute appropriately...
1021 if (gtgt->IsFrameworkOnApple()) {
1022 if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePrivateHeader) {
1023 attrs->AddObject(this->CreateString("Private"));
1024 } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePublicHeader) {
1025 attrs->AddObject(this->CreateString("Public"));
1029 // Add user-specified file attributes.
1030 cmValue extraFileAttributes = sf->GetProperty("XCODE_FILE_ATTRIBUTES");
1031 if (extraFileAttributes) {
1032 // Expand the list of attributes.
1033 std::vector<std::string> attributes = cmExpandedList(*extraFileAttributes);
1035 // Store the attributes.
1036 for (const auto& attribute : attributes) {
1037 attrs->AddObject(this->CreateString(attribute));
1041 settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
1044 buildFile->AddAttributeIfNotEmpty("settings", settings);
1049 void cmGlobalXCodeGenerator::AddXCodeProjBuildRule(
1050 cmGeneratorTarget* target, std::vector<cmSourceFile*>& sources) const
1052 std::string listfile =
1053 cmStrCat(target->GetLocalGenerator()->GetCurrentSourceDirectory(),
1055 cmSourceFile* srcCMakeLists = target->Makefile->GetOrCreateSource(
1056 listfile, false, cmSourceFileLocationKind::Known);
1057 if (!cm::contains(sources, srcCMakeLists)) {
1058 sources.push_back(srcCMakeLists);
1064 bool IsLinkPhaseLibraryExtension(const std::string& fileExt)
1066 // Empty file extension is a special case for paths to framework's
1067 // internal binary which could be MyFw.framework/Versions/*/MyFw
1068 return (fileExt == ".framework" || fileExt == ".a" || fileExt == ".o" ||
1069 fileExt == ".dylib" || fileExt == ".tbd" || fileExt.empty());
1071 bool IsLibraryType(const std::string& fileType)
1073 return (fileType == "wrapper.framework" || fileType == "archive.ar" ||
1074 fileType == "compiled.mach-o.objfile" ||
1075 fileType == "compiled.mach-o.dylib" ||
1076 fileType == "compiled.mach-o.executable" ||
1077 fileType == "sourcecode.text-based-dylib-definition");
1080 std::string GetDirectoryValueFromFileExtension(const std::string& dirExt)
1082 std::string ext = cmSystemTools::LowerCase(dirExt);
1083 if (ext == "framework") {
1084 return "wrapper.framework";
1086 if (ext == "xcassets") {
1087 return "folder.assetcatalog";
1092 std::string GetSourcecodeValueFromFileExtension(
1093 const std::string& _ext, const std::string& lang,
1094 bool& keepLastKnownFileType, const std::vector<std::string>& enabled_langs)
1096 std::string ext = cmSystemTools::LowerCase(_ext);
1097 std::string sourcecode = "sourcecode";
1100 keepLastKnownFileType = true;
1101 sourcecode = "compiled.mach-o.objfile";
1102 } else if (ext == "xctest") {
1103 sourcecode = "wrapper.cfbundle";
1104 } else if (ext == "xib") {
1105 keepLastKnownFileType = true;
1106 sourcecode = "file.xib";
1107 } else if (ext == "storyboard") {
1108 keepLastKnownFileType = true;
1109 sourcecode = "file.storyboard";
1110 } else if (ext == "mm" && !cm::contains(enabled_langs, "OBJCXX")) {
1111 sourcecode += ".cpp.objcpp";
1112 } else if (ext == "m" && !cm::contains(enabled_langs, "OBJC")) {
1113 sourcecode += ".c.objc";
1114 } else if (ext == "swift") {
1115 sourcecode += ".swift";
1116 } else if (ext == "plist") {
1117 sourcecode += ".text.plist";
1118 } else if (ext == "h") {
1119 sourcecode += ".c.h";
1120 } else if (ext == "hxx" || ext == "hpp" || ext == "txx" || ext == "pch" ||
1121 ext == "hh" || ext == "inl") {
1122 sourcecode += ".cpp.h";
1123 } else if (ext == "png" || ext == "gif" || ext == "jpg") {
1124 keepLastKnownFileType = true;
1125 sourcecode = "image";
1126 } else if (ext == "txt") {
1127 sourcecode += ".text";
1128 } else if (lang == "CXX") {
1129 sourcecode += ".cpp.cpp";
1130 } else if (lang == "C") {
1131 sourcecode += ".c.c";
1132 } else if (lang == "OBJCXX") {
1133 sourcecode += ".cpp.objcpp";
1134 } else if (lang == "OBJC") {
1135 sourcecode += ".c.objc";
1136 } else if (lang == "Fortran") {
1137 sourcecode += ".fortran.f90";
1138 } else if (lang == "ASM") {
1139 sourcecode += ".asm";
1140 } else if (ext == "metal") {
1141 sourcecode += ".metal";
1142 } else if (ext == "mig") {
1143 sourcecode += ".mig";
1144 } else if (ext == "tbd") {
1145 sourcecode += ".text-based-dylib-definition";
1146 } else if (ext == "a") {
1147 keepLastKnownFileType = true;
1148 sourcecode = "archive.ar";
1149 } else if (ext == "dylib") {
1150 keepLastKnownFileType = true;
1151 sourcecode = "compiled.mach-o.dylib";
1152 } else if (ext == "framework") {
1153 keepLastKnownFileType = true;
1154 sourcecode = "wrapper.framework";
1155 } else if (ext == "xcassets") {
1156 keepLastKnownFileType = true;
1157 sourcecode = "folder.assetcatalog";
1158 } else if (ext == "xcconfig") {
1159 keepLastKnownFileType = true;
1160 sourcecode = "text.xcconfig";
1164 // // Already specialized above or we leave sourcecode == "sourcecode"
1165 // // which is probably the most correct choice. Extensionless headers,
1166 // // for example... Or file types unknown to Xcode that do not map to a
1167 // // valid explicitFileType value.
1174 std::string GetTargetObjectDirArch(T const& target,
1175 const std::string& defaultVal)
1177 auto archs = cmExpandedList(target.GetSafeProperty("OSX_ARCHITECTURES"));
1178 if (archs.size() > 1) {
1179 return "$(CURRENT_ARCH)";
1180 } else if (archs.size() == 1) {
1181 return archs.front();
1189 // Extracts the framework directory, if path matches the framework syntax
1190 // otherwise returns the path untouched
1191 std::string cmGlobalXCodeGenerator::GetLibraryOrFrameworkPath(
1192 const std::string& path) const
1194 auto fwDescriptor = this->SplitFrameworkPath(path);
1196 return fwDescriptor->GetFrameworkPath();
1202 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReferenceFromPath(
1203 const std::string& fullpath, cmGeneratorTarget* target,
1204 const std::string& lang, cmSourceFile* sf)
1206 bool useLastKnownFileType = false;
1207 std::string fileType;
1209 if (cmValue e = sf->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
1211 } else if (cmValue l = sf->GetProperty("XCODE_LAST_KNOWN_FILE_TYPE")) {
1212 useLastKnownFileType = true;
1216 // Make a copy so that we can override it later
1217 std::string path = cmSystemTools::CollapseFullPath(fullpath);
1218 // Compute the extension without leading '.'.
1219 std::string ext = cmSystemTools::GetFilenameLastExtension(path);
1221 ext = ext.substr(1);
1223 if (fileType.empty()) {
1224 path = this->GetLibraryOrFrameworkPath(path);
1225 ext = cmSystemTools::GetFilenameLastExtension(path);
1227 ext = ext.substr(1);
1229 // If fullpath references a directory, then we need to specify
1230 // lastKnownFileType as folder in order for Xcode to be able to
1231 // open the contents of the folder.
1232 // (Xcode 4.6 does not like explicitFileType=folder).
1233 if (cmSystemTools::FileIsDirectory(path)) {
1234 fileType = GetDirectoryValueFromFileExtension(ext);
1235 useLastKnownFileType = true;
1237 if (ext.empty() && !sf) {
1238 // Special case for executable or library without extension
1239 // that is not a source file. We can't tell which without reading
1240 // its Mach-O header, but the file might not exist yet, so we
1241 // have to pick one here.
1242 useLastKnownFileType = true;
1243 fileType = "compiled.mach-o.executable";
1245 fileType = GetSourcecodeValueFromFileExtension(
1246 ext, lang, useLastKnownFileType, this->EnabledLangs);
1251 std::string key = GetGroupMapKeyFromPath(target, path);
1252 cmXCodeObject* fileRef = this->FileRefs[key];
1254 fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
1255 fileRef->SetComment(path);
1256 this->FileRefs[key] = fileRef;
1258 fileRef->AddAttribute("fileEncoding", this->CreateString("4"));
1259 fileRef->AddAttribute(useLastKnownFileType ? "lastKnownFileType"
1260 : "explicitFileType",
1261 this->CreateString(fileType));
1262 // Store the file path relative to the top of the source tree.
1263 if (!IsLibraryType(fileType)) {
1264 path = this->RelativeToSource(path);
1266 std::string name = cmSystemTools::GetFilenameName(path);
1267 const char* sourceTree =
1268 cmSystemTools::FileIsFullPath(path) ? "<absolute>" : "SOURCE_ROOT";
1269 fileRef->AddAttribute("name", this->CreateString(name));
1270 fileRef->AddAttribute("path", this->CreateString(path));
1271 fileRef->AddAttribute("sourceTree", this->CreateString(sourceTree));
1273 cmXCodeObject* group = this->GroupMap[key];
1274 if (!group && IsLibraryType(fileType)) {
1275 group = this->FrameworkGroup;
1276 this->GroupMap[key] = group;
1279 cmSystemTools::Error("Could not find a PBX group for " + key);
1282 cmXCodeObject* children = group->GetAttribute("children");
1283 if (!children->HasObject(fileRef)) {
1284 children->AddObject(fileRef);
1289 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReference(
1290 cmSourceFile* sf, cmGeneratorTarget* target)
1292 std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
1294 return this->CreateXCodeFileReferenceFromPath(sf->ResolveFullPath(), target,
1298 bool cmGlobalXCodeGenerator::SpecialTargetEmitted(std::string const& tname)
1300 if (tname == "ALL_BUILD" || tname == "install" || tname == "package" ||
1301 tname == "RUN_TESTS" || tname == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
1302 if (this->TargetDoneSet.find(tname) != this->TargetDoneSet.end()) {
1305 this->TargetDoneSet.insert(tname);
1311 void cmGlobalXCodeGenerator::SetCurrentLocalGenerator(cmLocalGenerator* gen)
1313 this->CurrentLocalGenerator = gen;
1314 this->CurrentMakefile = gen->GetMakefile();
1316 // Select the current set of configuration types.
1317 this->CurrentConfigurationTypes =
1318 this->CurrentMakefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
1321 struct cmSourceFilePathCompare
1323 bool operator()(cmSourceFile* l, cmSourceFile* r)
1325 return l->ResolveFullPath() < r->ResolveFullPath();
1329 struct cmCompareTargets
1331 bool operator()(cmXCodeObject* l, cmXCodeObject* r) const
1333 std::string const& a = l->GetTarget()->GetName();
1334 std::string const& b = r->GetTarget()->GetName();
1335 if (a == "ALL_BUILD") {
1338 if (b == "ALL_BUILD") {
1345 bool cmGlobalXCodeGenerator::CreateXCodeTargets(
1346 cmLocalGenerator* gen, std::vector<cmXCodeObject*>& targets)
1348 this->SetCurrentLocalGenerator(gen);
1349 std::vector<cmGeneratorTarget*> gts =
1350 this->GetLocalGeneratorTargetsInOrder(gen);
1351 for (auto gtgt : gts) {
1352 if (!this->CreateXCodeTarget(gtgt, targets)) {
1356 std::sort(targets.begin(), targets.end(), cmCompareTargets());
1360 bool cmGlobalXCodeGenerator::CreateXCodeTarget(
1361 cmGeneratorTarget* gtgt, std::vector<cmXCodeObject*>& targets)
1363 std::string targetName = gtgt->GetName();
1365 // make sure ALL_BUILD, INSTALL, etc are only done once
1366 if (this->SpecialTargetEmitted(targetName)) {
1370 if (!gtgt->IsInBuildSystem()) {
1374 for (std::string const& configName : this->CurrentConfigurationTypes) {
1375 gtgt->CheckCxxModuleStatus(configName);
1378 if (gtgt->HaveCxx20ModuleSources()) {
1379 gtgt->Makefile->IssueMessage(
1380 MessageType::FATAL_ERROR,
1381 cmStrCat("The \"", gtgt->GetName(),
1382 "\" target contains C++ module sources which are not "
1383 "supported by the generator"));
1386 auto& gtgt_visited = this->CommandsVisited[gtgt];
1387 auto& deps = this->GetTargetDirectDepends(gtgt);
1388 for (auto& d : deps) {
1389 // Take the union of visited source files of custom commands so far.
1390 // ComputeTargetOrder ensures our dependencies already visited their
1391 // custom commands and updated CommandsVisited.
1392 auto& dep_visited = this->CommandsVisited[d];
1393 gtgt_visited.insert(dep_visited.begin(), dep_visited.end());
1396 if (gtgt->GetType() == cmStateEnums::UTILITY ||
1397 gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
1398 gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1399 cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
1403 targets.push_back(t);
1407 // organize the sources
1408 std::vector<cmSourceFile*> commonSourceFiles;
1409 if (!gtgt->GetConfigCommonSourceFilesForXcode(commonSourceFiles)) {
1413 // Add CMakeLists.txt file for user convenience.
1414 this->AddXCodeProjBuildRule(gtgt, commonSourceFiles);
1416 // Add the Info.plist we are about to generate for an App Bundle.
1417 if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
1418 std::string plist = this->ComputeInfoPListLocation(gtgt);
1419 cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
1420 plist, true, cmSourceFileLocationKind::Known);
1421 commonSourceFiles.push_back(sf);
1424 std::sort(commonSourceFiles.begin(), commonSourceFiles.end(),
1425 cmSourceFilePathCompare());
1427 gtgt->ComputeObjectMapping();
1429 std::vector<cmXCodeObject*> externalObjFiles;
1430 std::vector<cmXCodeObject*> headerFiles;
1431 std::vector<cmXCodeObject*> resourceFiles;
1432 std::vector<cmXCodeObject*> sourceFiles;
1433 for (auto sourceFile : commonSourceFiles) {
1434 cmXCodeObject* xsf = this->CreateXCodeSourceFile(
1435 this->CurrentLocalGenerator, sourceFile, gtgt);
1436 cmXCodeObject* fr = xsf->GetAttribute("fileRef");
1437 cmXCodeObject* filetype =
1438 fr->GetObject()->GetAttribute("explicitFileType");
1440 filetype = fr->GetObject()->GetAttribute("lastKnownFileType");
1443 cmGeneratorTarget::SourceFileFlags tsFlags =
1444 gtgt->GetTargetSourceFileFlags(sourceFile);
1446 if (filetype && filetype->GetString() == "compiled.mach-o.objfile") {
1447 if (sourceFile->GetObjectLibrary().empty()) {
1448 externalObjFiles.push_back(xsf);
1450 } else if (this->IsHeaderFile(sourceFile) ||
1452 cmGeneratorTarget::SourceFileTypePrivateHeader) ||
1454 cmGeneratorTarget::SourceFileTypePublicHeader)) {
1455 headerFiles.push_back(xsf);
1456 } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource) {
1457 resourceFiles.push_back(xsf);
1458 } else if (!sourceFile->GetPropertyAsBool("HEADER_FILE_ONLY") &&
1459 !gtgt->IsSourceFilePartOfUnityBatch(
1460 sourceFile->ResolveFullPath())) {
1461 // Include this file in the build if it has a known language
1462 // and has not been listed as an ignored extension for this
1464 if (!this->CurrentLocalGenerator->GetSourceFileLanguage(*sourceFile)
1466 !this->IgnoreFile(sourceFile->GetExtension().c_str())) {
1467 sourceFiles.push_back(xsf);
1472 // some build phases only apply to bundles and/or frameworks
1473 bool isFrameworkTarget = gtgt->IsFrameworkOnApple();
1474 bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
1475 bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
1477 cmXCodeObject* buildFiles = nullptr;
1479 // create source build phase
1480 cmXCodeObject* sourceBuildPhase = nullptr;
1481 if (!sourceFiles.empty()) {
1482 sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
1483 sourceBuildPhase->SetComment("Sources");
1484 sourceBuildPhase->AddAttribute("buildActionMask",
1485 this->CreateString("2147483647"));
1486 buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1487 for (auto& sourceFile : sourceFiles) {
1488 buildFiles->AddObject(sourceFile);
1490 sourceBuildPhase->AddAttribute("files", buildFiles);
1491 sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1492 this->CreateString("0"));
1495 // create header build phase - only for framework targets
1496 cmXCodeObject* headerBuildPhase = nullptr;
1497 if (!headerFiles.empty() && isFrameworkTarget) {
1498 headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
1499 headerBuildPhase->SetComment("Headers");
1500 headerBuildPhase->AddAttribute("buildActionMask",
1501 this->CreateString("2147483647"));
1502 buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1503 for (auto& headerFile : headerFiles) {
1504 buildFiles->AddObject(headerFile);
1506 headerBuildPhase->AddAttribute("files", buildFiles);
1507 headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1508 this->CreateString("0"));
1511 // create resource build phase - only for framework or bundle targets
1512 cmXCodeObject* resourceBuildPhase = nullptr;
1513 if (!resourceFiles.empty() &&
1514 (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
1515 resourceBuildPhase =
1516 this->CreateObject(cmXCodeObject::PBXResourcesBuildPhase);
1517 resourceBuildPhase->SetComment("Resources");
1518 resourceBuildPhase->AddAttribute("buildActionMask",
1519 this->CreateString("2147483647"));
1520 buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1521 for (auto& resourceFile : resourceFiles) {
1522 buildFiles->AddObject(resourceFile);
1524 resourceBuildPhase->AddAttribute("files", buildFiles);
1525 resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1526 this->CreateString("0"));
1529 // create vector of "non-resource content file" build phases - only for
1530 // framework or bundle targets
1531 std::vector<cmXCodeObject*> contentBuildPhases;
1532 if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
1533 using mapOfVectorOfSourceFiles =
1534 std::map<std::string, std::vector<cmSourceFile*>>;
1535 mapOfVectorOfSourceFiles bundleFiles;
1536 for (auto sourceFile : commonSourceFiles) {
1537 cmGeneratorTarget::SourceFileFlags tsFlags =
1538 gtgt->GetTargetSourceFileFlags(sourceFile);
1539 if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeMacContent) {
1540 bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
1543 for (auto const& keySources : bundleFiles) {
1544 cmXCodeObject* copyFilesBuildPhase =
1545 this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
1546 copyFilesBuildPhase->SetComment("Copy files");
1547 copyFilesBuildPhase->AddAttribute("buildActionMask",
1548 this->CreateString("2147483647"));
1549 copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
1550 this->CreateString("6"));
1551 std::ostringstream ostr;
1552 if (gtgt->IsFrameworkOnApple()) {
1553 // dstPath in frameworks is relative to Versions/<version>
1554 ostr << keySources.first;
1555 } else if (keySources.first != "MacOS") {
1556 if (gtgt->Target->GetMakefile()->PlatformIsAppleEmbedded()) {
1557 ostr << keySources.first;
1559 // dstPath in bundles is relative to Contents/MacOS
1560 ostr << "../" << keySources.first;
1563 copyFilesBuildPhase->AddAttribute("dstPath",
1564 this->CreateString(ostr.str()));
1565 copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1566 this->CreateString("0"));
1567 buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1568 copyFilesBuildPhase->AddAttribute("files", buildFiles);
1569 for (auto sourceFile : keySources.second) {
1570 cmXCodeObject* xsf = this->CreateXCodeSourceFile(
1571 this->CurrentLocalGenerator, sourceFile, gtgt);
1572 buildFiles->AddObject(xsf);
1574 contentBuildPhases.push_back(copyFilesBuildPhase);
1578 // create vector of "resource content file" build phases - only for
1579 // framework or bundle targets
1580 if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
1581 using mapOfVectorOfSourceFiles =
1582 std::map<std::string, std::vector<cmSourceFile*>>;
1583 mapOfVectorOfSourceFiles bundleFiles;
1584 for (auto sourceFile : commonSourceFiles) {
1585 cmGeneratorTarget::SourceFileFlags tsFlags =
1586 gtgt->GetTargetSourceFileFlags(sourceFile);
1587 if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeDeepResource) {
1588 bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
1591 for (auto const& keySources : bundleFiles) {
1592 cmXCodeObject* copyFilesBuildPhase =
1593 this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
1594 copyFilesBuildPhase->SetComment("Copy files");
1595 copyFilesBuildPhase->AddAttribute("buildActionMask",
1596 this->CreateString("2147483647"));
1597 copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
1598 this->CreateString("7"));
1599 copyFilesBuildPhase->AddAttribute("dstPath",
1600 this->CreateString(keySources.first));
1601 copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1602 this->CreateString("0"));
1603 buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1604 copyFilesBuildPhase->AddAttribute("files", buildFiles);
1605 for (auto sourceFile : keySources.second) {
1606 cmXCodeObject* xsf = this->CreateXCodeSourceFile(
1607 this->CurrentLocalGenerator, sourceFile, gtgt);
1608 buildFiles->AddObject(xsf);
1610 contentBuildPhases.push_back(copyFilesBuildPhase);
1614 // Always create Link Binary With Libraries build phase
1615 cmXCodeObject* frameworkBuildPhase = nullptr;
1616 frameworkBuildPhase =
1617 this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
1618 frameworkBuildPhase->SetComment("Frameworks");
1619 frameworkBuildPhase->AddAttribute("buildActionMask",
1620 this->CreateString("2147483647"));
1621 buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1622 frameworkBuildPhase->AddAttribute("files", buildFiles);
1623 // Add all collected .o files to this build phase
1624 for (auto& externalObjFile : externalObjFiles) {
1625 buildFiles->AddObject(externalObjFile);
1627 frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1628 this->CreateString("0"));
1630 // create list of build phases and create the Xcode target
1631 cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1633 this->CreateCustomCommands(buildPhases, sourceBuildPhase, headerBuildPhase,
1634 resourceBuildPhase, contentBuildPhases,
1635 frameworkBuildPhase, gtgt);
1637 targets.push_back(this->CreateXCodeTarget(gtgt, buildPhases));
1641 void cmGlobalXCodeGenerator::ForceLinkerLanguages()
1643 for (const auto& localGenerator : this->LocalGenerators) {
1644 // All targets depend on the build-system check target.
1645 for (const auto& tgt : localGenerator->GetGeneratorTargets()) {
1646 // This makes sure all targets link using the proper language.
1647 this->ForceLinkerLanguage(tgt.get());
1652 void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
1654 // This matters only for targets that link.
1655 if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
1656 gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
1657 gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
1661 std::string llang = gtgt->GetLinkerLanguage("NOCONFIG");
1662 if (llang.empty()) {
1666 // If the language is compiled as a source trust Xcode to link with it.
1667 for (auto const& Language :
1669 ->GetLinkImplementation("NOCONFIG",
1670 cmGeneratorTarget::LinkInterfaceFor::Link)
1672 if (Language == llang) {
1677 // Allow empty source file list for iOS Sticker packs
1678 if (const char* productType = GetTargetProductType(gtgt)) {
1679 if (strcmp(productType,
1680 "com.apple.product-type.app-extension.messages-sticker-pack") ==
1685 // Add an empty source file to the target that compiles with the
1686 // linker language. This should convince Xcode to choose the proper
1688 cmMakefile* mf = gtgt->Target->GetMakefile();
1689 std::string fname = cmStrCat(
1690 gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
1691 gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
1693 cmGeneratedFileStream fout(fname);
1696 if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
1697 sf->SetProperty("LANGUAGE", llang);
1698 gtgt->AddSource(fname);
1702 bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
1704 return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
1705 sf->GetExtension());
1708 cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
1709 const char* name, const char* name2, cmGeneratorTarget* target,
1710 const std::vector<cmCustomCommand>& commands)
1712 if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
1715 cmXCodeObject* buildPhase =
1716 this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
1717 buildPhase->AddAttribute("buildActionMask",
1718 this->CreateString("2147483647"));
1719 cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1720 buildPhase->AddAttribute("files", buildFiles);
1721 buildPhase->AddAttribute("name", this->CreateString(name));
1722 buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1723 this->CreateString("0"));
1724 buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
1725 this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
1729 void cmGlobalXCodeGenerator::CreateCustomCommands(
1730 cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
1731 cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
1732 std::vector<cmXCodeObject*> const& contentBuildPhases,
1733 cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
1735 std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
1736 std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
1737 std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
1739 if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
1740 !gtgt->IsFrameworkOnApple()) {
1741 std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
1742 std::string str_so_file =
1743 cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
1744 std::string str_link_file =
1745 cmStrCat("$<TARGET_LINKER_FILE:", gtgt->GetName(), '>');
1746 cmCustomCommandLines cmd = cmMakeSingleCommandLine(
1747 { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
1748 str_file, str_so_file, str_link_file });
1750 cmCustomCommand command;
1751 command.SetCommandLines(cmd);
1752 command.SetComment("Creating symlinks");
1753 command.SetWorkingDirectory("");
1754 command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
1755 command.SetStdPipesUTF8(true);
1757 postbuild.push_back(std::move(command));
1760 cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
1761 cmXCodeObject* preBuildPhase = nullptr;
1762 cmXCodeObject* preLinkPhase = nullptr;
1763 cmXCodeObject* postBuildPhase = nullptr;
1765 if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
1766 // create prebuild phase
1768 this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
1769 // create prelink phase
1771 this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
1772 // create postbuild phase
1773 postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
1776 std::vector<cmSourceFile*> classes;
1777 if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
1780 // add all the sources
1781 std::vector<cmCustomCommand> commands;
1782 auto& visited = this->CommandsVisited[gtgt];
1783 for (auto sourceFile : classes) {
1784 if (sourceFile->GetCustomCommand() &&
1785 visited.insert(sourceFile).second) {
1786 commands.push_back(*sourceFile->GetCustomCommand());
1789 // create custom commands phase
1790 legacyCustomCommandsBuildPhase = this->CreateLegacyRunScriptBuildPhase(
1791 "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
1792 // create prebuild phase
1793 preBuildPhase = this->CreateLegacyRunScriptBuildPhase(
1794 "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
1795 // create prelink phase
1796 preLinkPhase = this->CreateLegacyRunScriptBuildPhase(
1797 "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
1798 // create postbuild phase
1799 postBuildPhase = this->CreateLegacyRunScriptBuildPhase(
1800 "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
1803 // The order here is the order they will be built in.
1804 // The order "headers, resources, sources" mimics a native project generated
1805 // from an xcode template...
1807 if (preBuildPhase) {
1808 buildPhases->AddObject(preBuildPhase);
1810 if (legacyCustomCommandsBuildPhase) {
1811 buildPhases->AddObject(legacyCustomCommandsBuildPhase);
1813 if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
1814 this->CreateRunScriptBuildPhases(buildPhases, gtgt);
1816 if (headerBuildPhase) {
1817 buildPhases->AddObject(headerBuildPhase);
1819 if (resourceBuildPhase) {
1820 buildPhases->AddObject(resourceBuildPhase);
1822 for (auto obj : contentBuildPhases) {
1823 buildPhases->AddObject(obj);
1825 if (sourceBuildPhase) {
1826 buildPhases->AddObject(sourceBuildPhase);
1829 buildPhases->AddObject(preLinkPhase);
1831 if (frameworkBuildPhase) {
1832 buildPhases->AddObject(frameworkBuildPhase);
1835 // When this build phase is present, it must be last. More build phases may
1836 // be added later for embedding things and they will insert themselves just
1837 // before this last build phase.
1838 if (postBuildPhase) {
1839 buildPhases->AddObject(postBuildPhase);
1843 void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
1844 cmXCodeObject* buildPhases, cmGeneratorTarget const* gt)
1846 std::vector<cmSourceFile*> sources;
1847 if (!gt->GetConfigCommonSourceFilesForXcode(sources)) {
1850 auto& visited = this->CommandsVisited[gt];
1851 for (auto sf : sources) {
1852 this->CreateRunScriptBuildPhases(buildPhases, sf, gt, visited);
1856 void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
1857 cmXCodeObject* buildPhases, cmSourceFile const* sf,
1858 cmGeneratorTarget const* gt, std::set<cmSourceFile const*>& visited)
1860 cmCustomCommand const* cc = sf->GetCustomCommand();
1861 if (cc && visited.insert(sf).second) {
1862 this->CustomCommandRoots[sf].insert(gt);
1863 if (std::vector<cmSourceFile*> const* depends = gt->GetSourceDepends(sf)) {
1864 for (cmSourceFile const* di : *depends) {
1865 this->CreateRunScriptBuildPhases(buildPhases, di, gt, visited);
1868 cmXCodeObject* buildPhase = this->CreateRunScriptBuildPhase(sf, gt, *cc);
1869 buildPhases->AddObject(buildPhase);
1873 cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
1874 cmSourceFile const* sf, cmGeneratorTarget const* gt,
1875 cmCustomCommand const& cc)
1877 std::set<std::string> allConfigInputs;
1878 std::set<std::string> allConfigOutputs;
1880 cmXCodeObject* buildPhase =
1881 this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
1882 cmStrCat(gt->GetName(), ':', sf->GetFullPath()));
1884 auto depfilesDirectory = cmStrCat(
1885 gt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/d/");
1886 auto depfilesPrefix = cmStrCat(depfilesDirectory, buildPhase->GetId(), ".");
1888 std::string shellScript = "set -e\n";
1889 for (std::string const& configName : this->CurrentConfigurationTypes) {
1890 cmCustomCommandGenerator ccg(
1891 cc, configName, this->CurrentLocalGenerator, true, {},
1892 [&depfilesPrefix](const std::string& config, const std::string&)
1893 -> std::string { return cmStrCat(depfilesPrefix, config, ".d"); });
1894 std::vector<std::string> realDepends;
1895 realDepends.reserve(ccg.GetDepends().size());
1896 for (auto const& d : ccg.GetDepends()) {
1898 if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
1899 realDepends.emplace_back(std::move(dep));
1903 allConfigInputs.insert(realDepends.begin(), realDepends.end());
1904 allConfigOutputs.insert(ccg.GetByproducts().begin(),
1905 ccg.GetByproducts().end());
1906 allConfigOutputs.insert(ccg.GetOutputs().begin(), ccg.GetOutputs().end());
1909 cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")", configName,
1910 "\"; then :\n", this->ConstructScript(ccg), "fi\n");
1913 if (!cc.GetDepfile().empty()) {
1914 buildPhase->AddAttribute(
1916 this->CreateString(cmStrCat(depfilesDirectory, buildPhase->GetId(),
1917 ".$(CONFIGURATION).d")));
1918 // to avoid spurious errors during first build, create empty dependency
1920 cmSystemTools::MakeDirectory(depfilesDirectory);
1921 for (std::string const& configName : this->CurrentConfigurationTypes) {
1922 auto file = cmStrCat(depfilesPrefix, configName, ".d");
1923 if (!cmSystemTools::FileExists(file)) {
1924 cmSystemTools::Touch(file, true);
1929 buildPhase->AddAttribute("buildActionMask",
1930 this->CreateString("2147483647"));
1931 cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1932 buildPhase->AddAttribute("files", buildFiles);
1935 if (!allConfigOutputs.empty()) {
1936 name = cmStrCat("Generate ",
1937 this->RelativeToBinary(*allConfigOutputs.begin()));
1939 name = sf->GetLocation().GetName();
1941 buildPhase->AddAttribute("name", this->CreateString(name));
1943 buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1944 this->CreateString("0"));
1945 buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
1946 buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
1947 buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
1949 bool symbolic = false;
1951 cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1952 for (std::string const& i : allConfigInputs) {
1953 inputPaths->AddUniqueObject(this->CreateString(i));
1955 if (cmSourceFile* isf =
1956 gt->GetLocalGenerator()->GetMakefile()->GetSource(
1957 i, cmSourceFileLocationKind::Known)) {
1958 symbolic = isf->GetPropertyAsBool("SYMBOLIC");
1962 buildPhase->AddAttribute("inputPaths", inputPaths);
1965 cmXCodeObject* outputPaths =
1966 this->CreateObject(cmXCodeObject::OBJECT_LIST);
1967 for (std::string const& o : allConfigOutputs) {
1968 outputPaths->AddUniqueObject(this->CreateString(o));
1970 if (cmSourceFile* osf =
1971 gt->GetLocalGenerator()->GetMakefile()->GetSource(
1972 o, cmSourceFileLocationKind::Known)) {
1973 symbolic = osf->GetPropertyAsBool("SYMBOLIC");
1977 buildPhase->AddAttribute("outputPaths", outputPaths);
1980 buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
1986 cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
1987 std::string const& name, cmGeneratorTarget const* gt,
1988 std::vector<cmCustomCommand> const& commands)
1990 if (commands.empty()) {
1994 std::set<std::string> allConfigOutputs;
1996 std::string shellScript = "set -e\n";
1997 for (std::string const& configName : this->CurrentConfigurationTypes) {
1998 shellScript = cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")",
1999 configName, "\"; then :\n");
2000 for (cmCustomCommand const& cc : commands) {
2001 cmCustomCommandGenerator ccg(cc, configName,
2002 this->CurrentLocalGenerator);
2003 shellScript = cmStrCat(shellScript, this->ConstructScript(ccg));
2004 allConfigOutputs.insert(ccg.GetByproducts().begin(),
2005 ccg.GetByproducts().end());
2007 shellScript = cmStrCat(shellScript, "fi\n");
2010 cmXCodeObject* buildPhase =
2011 this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
2012 cmStrCat(gt->GetName(), ':', name));
2013 buildPhase->AddAttribute("buildActionMask",
2014 this->CreateString("2147483647"));
2015 cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
2016 buildPhase->AddAttribute("files", buildFiles);
2017 buildPhase->AddAttribute("name", this->CreateString(name));
2018 buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
2019 this->CreateString("0"));
2020 buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
2021 buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
2022 buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
2024 cmXCodeObject* outputPaths =
2025 this->CreateObject(cmXCodeObject::OBJECT_LIST);
2026 for (std::string const& o : allConfigOutputs) {
2027 outputPaths->AddUniqueObject(this->CreateString(o));
2029 buildPhase->AddAttribute("outputPaths", outputPaths);
2031 buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
2037 void ReplaceScriptVars(std::string& cmd)
2039 cmSystemTools::ReplaceString(cmd, "$(CONFIGURATION)", "$CONFIGURATION");
2040 cmSystemTools::ReplaceString(cmd, "$(EFFECTIVE_PLATFORM_NAME)",
2041 "$EFFECTIVE_PLATFORM_NAME");
2045 std::string cmGlobalXCodeGenerator::ConstructScript(
2046 cmCustomCommandGenerator const& ccg)
2049 cmLocalGenerator* lg = this->CurrentLocalGenerator;
2050 std::string wd = ccg.GetWorkingDirectory();
2052 wd = lg->GetCurrentBinaryDirectory();
2054 wd = lg->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
2055 ReplaceScriptVars(wd);
2056 script = cmStrCat(script, " cd ", wd, "\n");
2057 for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
2058 std::string cmd = ccg.GetCommand(c);
2062 cmSystemTools::ReplaceString(cmd, "/./", "/");
2063 cmd = lg->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
2064 ccg.AppendArguments(c, cmd);
2065 ReplaceScriptVars(cmd);
2066 script = cmStrCat(script, " ", cmd, '\n');
2071 // This function removes each occurrence of the flag and returns the last one
2072 // (i.e., the dominant flag in GCC)
2073 std::string cmGlobalXCodeGenerator::ExtractFlag(const char* flag,
2076 std::string retFlag;
2077 std::string::size_type lastOccurancePos = flags.rfind(flag);
2079 while (lastOccurancePos != std::string::npos) {
2080 // increment pos, we use lastOccurancePos to reduce search space on next
2082 std::string::size_type pos = lastOccurancePos;
2083 if (pos == 0 || flags[pos - 1] == ' ') {
2084 while (pos < flags.size() && flags[pos] != ' ') {
2086 retFlag += flags[pos];
2093 // decrement lastOccurancePos while making sure we don't loop around
2094 // and become a very large positive number since size_type is unsigned
2095 lastOccurancePos = lastOccurancePos == 0 ? 0 : lastOccurancePos - 1;
2096 lastOccurancePos = flags.rfind(flag, lastOccurancePos);
2101 // This function removes each matching occurrence of the expression and
2102 // returns the last one (i.e., the dominant flag in GCC)
2103 std::string cmGlobalXCodeGenerator::ExtractFlagRegex(const char* exp,
2107 std::string retFlag;
2109 cmsys::RegularExpression regex(exp);
2110 assert(regex.is_valid());
2111 if (!regex.is_valid()) {
2115 std::string::size_type offset = 0;
2117 while (regex.find(&flags[offset])) {
2118 const std::string::size_type startPos = offset + regex.start(matchIndex);
2119 const std::string::size_type endPos = offset + regex.end(matchIndex);
2120 const std::string::size_type size = endPos - startPos;
2122 offset = startPos + 1;
2124 retFlag.assign(flags, startPos, size);
2125 flags.replace(startPos, size, size, ' ');
2131 //----------------------------------------------------------------------------
2132 // This function strips off Xcode attributes that do not target the current
2134 void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
2135 std::string const& configName, std::string& attribute)
2137 // Handle [variant=<config>] condition explicitly here.
2138 std::string::size_type beginVariant = attribute.find("[variant=");
2139 if (beginVariant == std::string::npos) {
2140 // There is no variant in this attribute.
2144 std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
2145 if (endVariant == std::string::npos) {
2146 // There is no terminating bracket.
2150 // Compare the variant to the configuration.
2151 std::string variant =
2152 attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
2153 if (variant == configName) {
2154 // The variant matches the configuration so use this
2155 // attribute but drop the [variant=<config>] condition.
2156 attribute.erase(beginVariant, endVariant - beginVariant + 1);
2158 // The variant does not match the configuration so
2159 // do not use this attribute.
2164 void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
2165 cmXCodeObject* buildphase, cmGeneratorTarget* target,
2166 std::vector<cmCustomCommand> const& commands, const char* name)
2168 std::string dir = cmStrCat(
2169 this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
2170 cmSystemTools::MakeDirectory(dir);
2171 std::string makefile =
2172 cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
2174 for (const auto& currentConfig : this->CurrentConfigurationTypes) {
2175 this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
2179 std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
2180 cdir = this->ConvertToRelativeForMake(cdir);
2181 std::string makecmd =
2182 cmStrCat("make -C ", cdir, " -f ",
2183 this->ConvertToRelativeForMake((makefile + "$CONFIGURATION")),
2184 " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
2185 buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
2186 buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
2189 void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
2190 const char* makefileBasename, cmGeneratorTarget* target,
2191 std::vector<cmCustomCommand> const& commands, const std::string& configName)
2193 std::string makefileName = cmStrCat(makefileBasename, configName);
2194 cmGeneratedFileStream makefileStream(makefileName);
2195 if (!makefileStream) {
2198 makefileStream.SetCopyIfDifferent(true);
2199 makefileStream << "# Generated by CMake, DO NOT EDIT\n";
2200 makefileStream << "# Custom rules for " << target->GetName() << "\n";
2202 // disable the implicit rules
2203 makefileStream << ".SUFFIXES: "
2206 // have all depend on all outputs
2207 makefileStream << "all: ";
2208 std::map<const cmCustomCommand*, std::string> tname;
2210 for (auto const& command : commands) {
2211 cmCustomCommandGenerator ccg(command, configName,
2212 this->CurrentLocalGenerator);
2213 if (ccg.GetNumberOfCommands() > 0) {
2214 const std::vector<std::string>& outputs = ccg.GetOutputs();
2215 if (!outputs.empty()) {
2216 for (auto const& output : outputs) {
2217 makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(output);
2220 std::ostringstream str;
2221 str << "_buildpart_" << count++;
2222 tname[&ccg.GetCC()] = target->GetName() + str.str();
2223 makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
2227 makefileStream << "\n\n";
2229 auto depfilesDirectory =
2230 cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
2233 for (auto const& command : commands) {
2234 cmCustomCommandGenerator ccg(
2235 command, configName, this->CurrentLocalGenerator, true, {},
2236 [this, &depfilesDirectory](const std::string& config,
2237 const std::string& file) -> std::string {
2240 this->GetObjectId(cmXCodeObject::PBXShellScriptBuildPhase, file),
2244 auto depfile = ccg.GetInternalDepfile();
2245 if (!depfile.empty()) {
2246 makefileStream << "include "
2247 << cmSystemTools::ConvertToOutputPath(depfile) << "\n\n";
2249 cmSystemTools::MakeDirectory(depfilesDirectory);
2250 if (!cmSystemTools::FileExists(depfile)) {
2251 cmSystemTools::Touch(depfile, true);
2255 std::vector<std::string> realDepends;
2256 realDepends.reserve(ccg.GetDepends().size());
2257 for (auto const& d : ccg.GetDepends()) {
2259 if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
2260 realDepends.emplace_back(std::move(dep));
2264 if (ccg.GetNumberOfCommands() > 0) {
2265 makefileStream << "\n";
2266 const std::vector<std::string>& outputs = ccg.GetOutputs();
2267 if (!outputs.empty()) {
2268 // There is at least one output, start the rule for it
2269 const char* sep = "";
2270 for (auto const& output : outputs) {
2271 makefileStream << sep << this->ConvertToRelativeForMake(output);
2274 makefileStream << ": ";
2276 // There are no outputs. Use the generated force rule name.
2277 makefileStream << tname[&ccg.GetCC()] << ": ";
2279 for (auto const& dep : realDepends) {
2280 makefileStream << "\\\n" << this->ConvertToRelativeForMake(dep);
2282 makefileStream << "\n";
2284 if (const char* comment = ccg.GetComment()) {
2285 std::string echo_cmd =
2287 (this->CurrentLocalGenerator->EscapeForShell(
2288 comment, ccg.GetCC().GetEscapeAllowMakeVars())));
2289 makefileStream << "\t" << echo_cmd << "\n";
2292 // Add each command line to the set of commands.
2293 for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
2294 // Build the command line in a single string.
2295 std::string cmd2 = ccg.GetCommand(c);
2296 cmSystemTools::ReplaceString(cmd2, "/./", "/");
2297 cmd2 = this->ConvertToRelativeForMake(cmd2);
2299 std::string wd = ccg.GetWorkingDirectory();
2302 cmd += this->ConvertToRelativeForMake(wd);
2306 ccg.AppendArguments(c, cmd);
2307 makefileStream << "\t" << cmd << "\n";
2310 // Symbolic inputs are not expected to exist, so add dummy rules.
2311 for (auto const& dep : realDepends) {
2312 if (cmSourceFile* dsf =
2313 target->GetLocalGenerator()->GetMakefile()->GetSource(
2314 dep, cmSourceFileLocationKind::Known)) {
2315 if (dsf->GetPropertyAsBool("SYMBOLIC")) {
2316 makefileStream << this->ConvertToRelativeForMake(dep) << ":\n";
2324 void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
2325 cmGeneratorTarget* target, cmXCodeObject* buildSettings,
2326 const std::string& configName)
2328 // For now, only EXECUTABLE is concerned
2329 if (target->GetType() != cmStateEnums::EXECUTABLE) {
2333 const char* PICValue = target->GetLinkPIEProperty(configName);
2334 if (PICValue == nullptr) {
2335 // POSITION_INDEPENDENT_CODE is not set
2339 buildSettings->AddAttribute(
2340 "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
2343 void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
2344 cmXCodeObject* buildSettings,
2345 const std::string& configName)
2347 if (!gtgt->IsInBuildSystem()) {
2351 std::string defFlags;
2352 bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
2353 (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
2354 bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
2355 (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
2356 (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
2358 // Compute the compilation flags for each language.
2359 std::set<std::string> languages;
2360 gtgt->GetLanguages(languages, configName);
2361 std::map<std::string, std::string> cflags;
2362 for (auto const& lang : languages) {
2363 std::string& flags = cflags[lang];
2365 // Add language-specific flags.
2366 this->CurrentLocalGenerator->AddLanguageFlags(
2367 flags, gtgt, cmBuildStep::Compile, lang, configName);
2369 if (gtgt->IsIPOEnabled(lang, configName)) {
2370 this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
2373 // Add shared-library flags if needed.
2374 this->CurrentLocalGenerator->AddCMP0018Flags(flags, gtgt, lang,
2377 this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
2379 this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
2383 std::string llang = gtgt->GetLinkerLanguage(configName);
2384 if (binary && llang.empty()) {
2385 cmSystemTools::Error(
2386 "CMake can not determine linker language for target: " +
2391 // Choose a language to use for target-wide preprocessor definitions.
2392 static const char* ppLangs[] = { "CXX", "C", "OBJCXX", "OBJC" };
2393 std::string langForPreprocessorDefinitions;
2394 if (cm::contains(ppLangs, llang)) {
2395 langForPreprocessorDefinitions = llang;
2397 for (const char* l : ppLangs) {
2398 if (languages.count(l)) {
2399 langForPreprocessorDefinitions = l;
2405 if (gtgt->IsIPOEnabled(llang, configName)) {
2406 const char* ltoValue =
2407 this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
2408 buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
2411 // Handle PIE linker configuration
2412 this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
2415 this->CurrentLocalGenerator->AppendFlags(
2416 defFlags, this->CurrentMakefile->GetDefineFlags());
2418 // Add preprocessor definitions for this target and configuration.
2419 BuildObjectListOrString ppDefs(this, true);
2420 this->AppendDefines(
2421 ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
2422 if (const std::string* exportMacro = gtgt->GetExportMacro()) {
2423 // Add the export symbol definition for shared library objects.
2424 this->AppendDefines(ppDefs, exportMacro->c_str());
2426 std::vector<std::string> targetDefines;
2427 if (!langForPreprocessorDefinitions.empty()) {
2428 gtgt->GetCompileDefinitions(targetDefines, configName,
2429 langForPreprocessorDefinitions);
2431 this->AppendDefines(ppDefs, targetDefines);
2432 buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
2433 ppDefs.CreateList());
2434 if (languages.count("Swift")) {
2435 // Swift uses a separate attribute for definitions.
2436 std::vector<std::string> targetSwiftDefines;
2437 gtgt->GetCompileDefinitions(targetSwiftDefines, configName, "Swift");
2438 // Remove the '=value' parts, as Swift does not support them.
2439 std::for_each(targetSwiftDefines.begin(), targetSwiftDefines.end(),
2440 [](std::string& def) {
2441 std::string::size_type pos = def.find('=');
2442 if (pos != std::string::npos) {
2446 if (this->XcodeVersion < 80) {
2447 std::string defineString;
2448 std::set<std::string> defines(targetSwiftDefines.begin(),
2449 targetSwiftDefines.end());
2450 this->CurrentLocalGenerator->JoinDefines(defines, defineString, "Swift");
2451 cflags["Swift"] += " " + defineString;
2453 BuildObjectListOrString swiftDefs(this, true);
2454 this->AppendDefines(swiftDefs, targetSwiftDefines);
2455 buildSettings->AddAttribute("SWIFT_ACTIVE_COMPILATION_CONDITIONS",
2456 swiftDefs.CreateList());
2460 std::string extraLinkOptionsVar;
2461 std::string extraLinkOptions;
2462 if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
2463 extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
2464 } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
2465 extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
2466 } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
2467 extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
2469 if (!extraLinkOptionsVar.empty()) {
2470 this->CurrentLocalGenerator->AddConfigVariableFlags(
2471 extraLinkOptions, extraLinkOptionsVar, configName);
2474 if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
2475 gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
2476 this->CurrentLocalGenerator->GetStaticLibraryFlags(
2477 extraLinkOptions, configName, llang, gtgt);
2479 cmValue targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
2480 if (targetLinkFlags) {
2481 this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
2484 if (!configName.empty()) {
2485 std::string linkFlagsVar =
2486 cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
2487 if (cmValue linkFlags = gtgt->GetProperty(linkFlagsVar)) {
2488 this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
2491 std::vector<std::string> opts;
2492 gtgt->GetLinkOptions(opts, configName, llang);
2493 // LINK_OPTIONS are escaped.
2494 this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
2497 // Set target-specific architectures.
2498 std::vector<std::string> archs;
2499 gtgt->GetAppleArchs(configName, archs);
2501 if (!archs.empty()) {
2502 // Enable ARCHS attribute.
2503 buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
2505 // Store ARCHS value.
2506 if (archs.size() == 1) {
2507 buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
2509 cmXCodeObject* archObjects =
2510 this->CreateObject(cmXCodeObject::OBJECT_LIST);
2511 for (auto& arch : archs) {
2512 archObjects->AddObject(this->CreateString(arch));
2514 buildSettings->AddAttribute("ARCHS", archObjects);
2518 // Get the product name components.
2519 std::string pnprefix;
2521 std::string pnsuffix;
2522 gtgt->GetFullNameComponents(pnprefix, pnbase, pnsuffix, configName);
2524 cmValue version = gtgt->GetProperty("VERSION");
2525 cmValue soversion = gtgt->GetProperty("SOVERSION");
2526 if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
2528 soversion = nullptr;
2530 if (version && !soversion) {
2531 soversion = version;
2533 if (!version && soversion) {
2534 version = soversion;
2537 std::string realName = pnbase;
2538 std::string soName = pnbase;
2539 if (version && soversion) {
2541 realName += *version;
2543 soName += *soversion;
2546 if (gtgt->CanCompileSources()) {
2547 std::string const tmpDir =
2548 this->GetTargetTempDir(gtgt, this->GetCMakeCFGIntDir());
2549 buildSettings->AddAttribute("TARGET_TEMP_DIR", this->CreateString(tmpDir));
2552 if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
2553 // We cannot suppress the archive, so hide it with intermediate files.
2556 outDir = gtgt->GetDirectory(configName);
2558 buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
2559 this->CreateString(outDir));
2562 // Set attributes to specify the proper name for the target.
2563 std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
2564 if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
2565 gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
2566 gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
2567 gtgt->GetType() == cmStateEnums::EXECUTABLE) {
2569 if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
2573 buildSettings->AddAttribute("EXECUTABLE_PREFIX",
2574 this->CreateString(pnprefix));
2575 buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
2576 this->CreateString(pnsuffix));
2579 // Store the product name for all target types.
2580 buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
2582 // Handle settings for each target type.
2583 switch (gtgt->GetType()) {
2584 case cmStateEnums::STATIC_LIBRARY:
2585 if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
2586 std::string fw_version = gtgt->GetFrameworkVersion();
2587 buildSettings->AddAttribute("FRAMEWORK_VERSION",
2588 this->CreateString(fw_version));
2589 cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2591 buildSettings->AddAttribute("WRAPPER_EXTENSION",
2592 this->CreateString(*ext));
2595 std::string plist = this->ComputeInfoPListLocation(gtgt);
2596 // Xcode will create the final version of Info.plist at build time,
2597 // so let it replace the framework name. This avoids creating
2598 // a per-configuration Info.plist file.
2599 this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
2600 gtgt, "$(EXECUTABLE_NAME)", plist);
2601 buildSettings->AddAttribute("INFOPLIST_FILE",
2602 this->CreateString(plist));
2603 buildSettings->AddAttribute("MACH_O_TYPE",
2604 this->CreateString("staticlib"));
2606 buildSettings->AddAttribute("LIBRARY_STYLE",
2607 this->CreateString("STATIC"));
2611 case cmStateEnums::OBJECT_LIBRARY: {
2612 buildSettings->AddAttribute("LIBRARY_STYLE",
2613 this->CreateString("STATIC"));
2617 case cmStateEnums::MODULE_LIBRARY: {
2618 buildSettings->AddAttribute("LIBRARY_STYLE",
2619 this->CreateString("BUNDLE"));
2620 if (gtgt->IsCFBundleOnApple()) {
2621 // It turns out that a BUNDLE is basically the same
2622 // in many ways as an application bundle, as far as
2624 std::string createFlags = this->LookupFlags(
2625 "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", "-bundle");
2626 if (!createFlags.empty()) {
2627 extraLinkOptions += " ";
2628 extraLinkOptions += createFlags;
2630 cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2632 buildSettings->AddAttribute("WRAPPER_EXTENSION",
2633 this->CreateString(*ext));
2635 std::string plist = this->ComputeInfoPListLocation(gtgt);
2636 // Xcode will create the final version of Info.plist at build time,
2637 // so let it replace the cfbundle name. This avoids creating
2638 // a per-configuration Info.plist file. The cfbundle plist
2639 // is very similar to the application bundle plist
2640 this->CurrentLocalGenerator->GenerateAppleInfoPList(
2641 gtgt, "$(EXECUTABLE_NAME)", plist);
2642 buildSettings->AddAttribute("INFOPLIST_FILE",
2643 this->CreateString(plist));
2645 buildSettings->AddAttribute("MACH_O_TYPE",
2646 this->CreateString("mh_bundle"));
2647 buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
2648 this->CreateString("NO"));
2649 // Add the flags to create an executable.
2650 std::string createFlags =
2651 this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
2652 if (!createFlags.empty()) {
2653 extraLinkOptions += " ";
2654 extraLinkOptions += createFlags;
2659 case cmStateEnums::SHARED_LIBRARY: {
2660 if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
2661 std::string fw_version = gtgt->GetFrameworkVersion();
2662 buildSettings->AddAttribute("FRAMEWORK_VERSION",
2663 this->CreateString(fw_version));
2664 cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2666 buildSettings->AddAttribute("WRAPPER_EXTENSION",
2667 this->CreateString(*ext));
2670 std::string plist = this->ComputeInfoPListLocation(gtgt);
2671 // Xcode will create the final version of Info.plist at build time,
2672 // so let it replace the framework name. This avoids creating
2673 // a per-configuration Info.plist file.
2674 this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
2675 gtgt, "$(EXECUTABLE_NAME)", plist);
2676 buildSettings->AddAttribute("INFOPLIST_FILE",
2677 this->CreateString(plist));
2679 // Add the flags to create a shared library.
2680 std::string createFlags = this->LookupFlags(
2681 "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", "-dynamiclib");
2682 if (!createFlags.empty()) {
2683 extraLinkOptions += " ";
2684 extraLinkOptions += createFlags;
2688 buildSettings->AddAttribute("LIBRARY_STYLE",
2689 this->CreateString("DYNAMIC"));
2692 case cmStateEnums::EXECUTABLE: {
2693 // Add the flags to create an executable.
2694 std::string createFlags =
2695 this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
2696 if (!createFlags.empty()) {
2697 extraLinkOptions += " ";
2698 extraLinkOptions += createFlags;
2701 // Handle bundles and normal executables separately.
2702 if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
2703 cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2705 buildSettings->AddAttribute("WRAPPER_EXTENSION",
2706 this->CreateString(*ext));
2708 std::string plist = this->ComputeInfoPListLocation(gtgt);
2709 // Xcode will create the final version of Info.plist at build time,
2710 // so let it replace the executable name. This avoids creating
2711 // a per-configuration Info.plist file.
2712 this->CurrentLocalGenerator->GenerateAppleInfoPList(
2713 gtgt, "$(EXECUTABLE_NAME)", plist);
2714 buildSettings->AddAttribute("INFOPLIST_FILE",
2715 this->CreateString(plist));
2722 BuildObjectListOrString dirs(this, true);
2723 BuildObjectListOrString fdirs(this, true);
2724 BuildObjectListOrString sysdirs(this, true);
2725 BuildObjectListOrString sysfdirs(this, true);
2726 const bool emitSystemIncludes = this->XcodeVersion >= 83;
2728 // Choose a language to use for target-wide include directories.
2729 std::string const& langForIncludes = llang;
2730 std::vector<std::string> includes;
2731 if (!langForIncludes.empty()) {
2732 this->CurrentLocalGenerator->GetIncludeDirectories(
2733 includes, gtgt, langForIncludes, configName);
2735 std::set<std::string> emitted;
2736 emitted.insert("/System/Library/Frameworks");
2738 for (auto& include : includes) {
2739 if (this->NameResolvesToFramework(include)) {
2740 std::string frameworkDir = cmStrCat(include, "/../");
2741 frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
2742 if (emitted.insert(frameworkDir).second) {
2743 std::string incpath = this->XCodeEscapePath(frameworkDir);
2744 if (emitSystemIncludes &&
2745 gtgt->IsSystemIncludeDirectory(include, configName,
2747 sysfdirs.Add(incpath);
2753 std::string incpath = this->XCodeEscapePath(include);
2754 if (emitSystemIncludes &&
2755 gtgt->IsSystemIncludeDirectory(include, configName,
2757 sysdirs.Add(incpath);
2763 // Add framework search paths needed for linking.
2764 if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
2765 for (auto const& fwDir : cli->GetFrameworkPaths()) {
2766 if (emitted.insert(fwDir).second) {
2767 std::string incpath = this->XCodeEscapePath(fwDir);
2768 if (emitSystemIncludes &&
2769 gtgt->IsSystemIncludeDirectory(fwDir, configName,
2771 sysfdirs.Add(incpath);
2778 if (!fdirs.IsEmpty()) {
2779 buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
2781 if (!dirs.IsEmpty()) {
2782 buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
2783 if (languages.count("Swift")) {
2784 buildSettings->AddAttribute("SWIFT_INCLUDE_PATHS", dirs.CreateList());
2787 if (!sysfdirs.IsEmpty()) {
2788 buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
2789 sysfdirs.CreateList());
2791 if (!sysdirs.IsEmpty()) {
2792 buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
2793 sysdirs.CreateList());
2796 if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
2797 // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
2798 // system include directory awareness. We need to also keep on setting
2799 // HEADER_SEARCH_PATHS to work around a missing compile options flag for
2800 // GNU assembly files (#16449)
2801 for (auto const& language : languages) {
2802 std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
2803 includes, gtgt, language, configName);
2805 if (!includeFlags.empty()) {
2806 cflags[language] += " " + includeFlags;
2811 bool same_gflags = true;
2812 std::map<std::string, std::string> gflags;
2813 std::string const* last_gflag = nullptr;
2814 std::string optLevel = "0";
2816 // Minimal map of flags to build settings.
2817 for (auto const& language : languages) {
2818 std::string& flags = cflags[language];
2819 std::string& gflag = gflags[language];
2821 this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
2822 if (oflag.size() == 2) {
2824 } else if (oflag.size() > 2) {
2825 optLevel = oflag.substr(2);
2827 gflag = this->ExtractFlag("-g", flags);
2828 // put back gdwarf-2 if used since there is no way
2829 // to represent it in the gui, but we still want debug yes
2830 if (gflag == "-gdwarf-2") {
2834 if (last_gflag && *last_gflag != gflag) {
2835 same_gflags = false;
2837 last_gflag = &gflag;
2840 const char* debugStr = "YES";
2842 // We can't set the Xcode flag differently depending on the language,
2843 // so put them back in this case.
2844 for (auto const& language : languages) {
2845 cflags[language] += " ";
2846 cflags[language] += gflags[language];
2849 } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0")) {
2853 // extract C++ stdlib
2854 for (auto const& language : languages) {
2855 if (language != "CXX" && language != "OBJCXX") {
2858 std::string& flags = cflags[language];
2861 this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
2862 if (stdlib.size() > 8) {
2863 const auto cxxLibrary = stdlib.substr(8);
2864 if (language == "CXX" ||
2865 !buildSettings->GetAttribute("CLANG_CXX_LIBRARY")) {
2866 buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
2867 this->CreateString(cxxLibrary));
2872 buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
2873 this->CreateString("YES"));
2874 buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
2875 this->CreateString(debugStr));
2876 buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
2877 this->CreateString(optLevel));
2878 buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
2879 this->CreateString("NO"));
2880 buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
2881 this->CreateString("NO"));
2883 for (auto const& language : languages) {
2884 std::string flags = cflags[language] + " " + defFlags;
2885 if (language == "CXX" || language == "OBJCXX") {
2886 if (language == "CXX" ||
2887 !buildSettings->GetAttribute("OTHER_CPLUSPLUSFLAGS")) {
2888 buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
2889 this->CreateString(flags));
2891 } else if (language == "Fortran") {
2892 buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
2893 this->CreateString(flags));
2894 } else if (language == "C" || language == "OBJC") {
2895 if (language == "C" || !buildSettings->GetAttribute("OTHER_CFLAGS")) {
2896 buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
2898 } else if (language == "Swift") {
2899 buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
2900 this->CreateString(flags));
2904 // Add Fortran source format attribute if property is set.
2905 const char* format = nullptr;
2906 std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
2907 switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
2908 case cmOutputConverter::FortranFormatFixed:
2911 case cmOutputConverter::FortranFormatFree:
2918 buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
2919 this->CreateString(format));
2922 // Create the INSTALL_PATH attribute.
2923 std::string install_name_dir;
2924 if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
2925 // Get the install_name directory for the build tree.
2926 install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
2927 // Xcode doesn't create the correct install_name in some cases.
2928 // That is, if the INSTALL_PATH is empty, or if we have versioning
2929 // of dylib libraries, we want to specify the install_name.
2930 // This is done by adding a link flag to create an install_name
2931 // with just the library soname.
2932 std::string install_name;
2933 if (!install_name_dir.empty()) {
2934 // Convert to a path for the native build tool.
2935 cmSystemTools::ConvertToUnixSlashes(install_name_dir);
2936 install_name += install_name_dir;
2937 install_name += "/";
2939 install_name += gtgt->GetSOName(configName);
2941 if ((realName != soName) || install_name_dir.empty()) {
2942 install_name_dir = "";
2943 extraLinkOptions += " -install_name ";
2944 extraLinkOptions += XCodeEscapePath(install_name);
2947 buildSettings->AddAttribute("INSTALL_PATH",
2948 this->CreateString(install_name_dir));
2950 // Create the LD_RUNPATH_SEARCH_PATHS
2951 cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
2953 std::string search_paths;
2954 std::vector<std::string> runtimeDirs;
2955 pcli->GetRPath(runtimeDirs, false);
2956 // runpath dirs needs to be unique to prevent corruption
2957 std::set<std::string> unique_dirs;
2959 for (auto runpath : runtimeDirs) {
2960 runpath = this->ExpandCFGIntDir(runpath, configName);
2962 if (unique_dirs.find(runpath) == unique_dirs.end()) {
2963 unique_dirs.insert(runpath);
2964 if (!search_paths.empty()) {
2965 search_paths += " ";
2967 search_paths += this->XCodeEscapePath(runpath);
2970 if (!search_paths.empty()) {
2971 buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
2972 this->CreateString(search_paths));
2976 buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
2977 this->CreateString(extraLinkOptions));
2978 buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
2979 buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
2980 buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
2981 cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
2982 group->AddObject(this->CreateString("$(inherited)"));
2983 buildSettings->AddAttribute("WARNING_CFLAGS", group);
2985 // Runtime version information.
2986 if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
2991 // MACHO_CURRENT_VERSION or VERSION -> current_version
2992 gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
2994 std::ostringstream v;
2996 // Xcode always wants at least 1.0.0 or nothing
2997 if (!(major == 0 && minor == 0 && patch == 0)) {
2998 v << major << "." << minor << "." << patch;
3000 buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
3001 this->CreateString(v.str()));
3003 // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
3004 gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
3005 major, minor, patch);
3006 std::ostringstream vso;
3008 // Xcode always wants at least 1.0.0 or nothing
3009 if (!(major == 0 && minor == 0 && patch == 0)) {
3010 vso << major << "." << minor << "." << patch;
3012 buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
3013 this->CreateString(vso.str()));
3016 // Precompile Headers
3017 std::string pchHeader = gtgt->GetPchHeader(configName, llang);
3018 if (!pchHeader.empty()) {
3019 buildSettings->AddAttribute("GCC_PREFIX_HEADER",
3020 this->CreateString(pchHeader));
3021 buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
3022 this->CreateString("YES"));
3025 // put this last so it can override existing settings
3026 // Convert "XCODE_ATTRIBUTE_*" properties directly.
3028 for (auto const& prop : gtgt->GetPropertyKeys()) {
3029 if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
3030 std::string attribute = prop.substr(16);
3031 this->FilterConfigurationAttribute(configName, attribute);
3032 if (!attribute.empty()) {
3033 std::string const& pr = gtgt->GetSafeProperty(prop);
3034 std::string processed = cmGeneratorExpression::Evaluate(
3035 pr, this->CurrentLocalGenerator, configName);
3036 buildSettings->AddAttribute(attribute,
3037 this->CreateString(processed));
3044 cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
3045 cmGeneratorTarget* gtgt)
3047 cmXCodeObject* shellBuildPhase = this->CreateObject(
3048 cmXCodeObject::PBXShellScriptBuildPhase, gtgt->GetName());
3049 shellBuildPhase->AddAttribute("buildActionMask",
3050 this->CreateString("2147483647"));
3051 cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3052 shellBuildPhase->AddAttribute("files", buildFiles);
3053 cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3054 shellBuildPhase->AddAttribute("inputPaths", inputPaths);
3055 cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3056 shellBuildPhase->AddAttribute("outputPaths", outputPaths);
3057 shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
3058 this->CreateString("0"));
3059 shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
3060 shellBuildPhase->AddAttribute(
3061 "shellScript", this->CreateString("# shell script goes here\nexit 0"));
3062 shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
3064 cmXCodeObject* target =
3065 this->CreateObject(cmXCodeObject::PBXAggregateTarget);
3066 target->SetComment(gtgt->GetName());
3067 cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3068 std::vector<cmXCodeObject*> emptyContentVector;
3069 this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
3070 emptyContentVector, nullptr, gtgt);
3071 target->AddAttribute("buildPhases", buildPhases);
3072 this->AddConfigurations(target, gtgt);
3073 cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3074 target->AddAttribute("dependencies", dependencies);
3075 target->AddAttribute("name", this->CreateString(gtgt->GetName()));
3076 target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
3077 target->SetTarget(gtgt);
3078 this->XCodeObjectMap[gtgt] = target;
3080 // Add source files without build rules for editing convenience.
3081 if (gtgt->GetType() != cmStateEnums::GLOBAL_TARGET &&
3082 gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
3083 std::vector<cmSourceFile*> sources;
3084 if (!gtgt->GetConfigCommonSourceFilesForXcode(sources)) {
3088 // Add CMakeLists.txt file for user convenience.
3089 this->AddXCodeProjBuildRule(gtgt, sources);
3091 for (auto sourceFile : sources) {
3092 if (!sourceFile->GetIsGenerated()) {
3093 this->CreateXCodeFileReference(sourceFile, gtgt);
3098 target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
3103 std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
3104 cmGeneratorTarget* gtgt)
3106 std::vector<std::string> const configVector = cmExpandedList(
3107 this->CurrentMakefile->GetRequiredDefinition("CMAKE_CONFIGURATION_TYPES"));
3108 cmXCodeObject* configlist =
3109 this->CreateObject(cmXCodeObject::XCConfigurationList);
3110 cmXCodeObject* buildConfigurations =
3111 this->CreateObject(cmXCodeObject::OBJECT_LIST);
3112 configlist->AddAttribute("buildConfigurations", buildConfigurations);
3113 std::string comment = cmStrCat("Build configuration list for ",
3114 cmXCodeObject::PBXTypeNames[target->GetIsA()],
3115 " \"", gtgt->GetName(), '"');
3116 configlist->SetComment(comment);
3117 target->AddAttribute("buildConfigurationList",
3118 this->CreateObjectReference(configlist));
3119 for (auto const& i : configVector) {
3120 cmXCodeObject* config =
3121 this->CreateObject(cmXCodeObject::XCBuildConfiguration);
3122 buildConfigurations->AddObject(config);
3123 cmXCodeObject* buildSettings =
3124 this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
3125 this->CreateBuildSettings(gtgt, buildSettings, i);
3126 config->AddAttribute("name", this->CreateString(i));
3127 config->SetComment(i);
3128 config->AddAttribute("buildSettings", buildSettings);
3130 this->CreateTargetXCConfigSettings(gtgt, config, i);
3132 if (!configVector.empty()) {
3133 configlist->AddAttribute("defaultConfigurationName",
3134 this->CreateString(configVector[0]));
3135 configlist->AddAttribute("defaultConfigurationIsVisible",
3136 this->CreateString("0"));
3137 return configVector[0];
3142 void cmGlobalXCodeGenerator::CreateGlobalXCConfigSettings(
3143 cmLocalGenerator* root, cmXCodeObject* config, const std::string& configName)
3145 auto xcconfig = cmGeneratorExpression::Evaluate(
3146 this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
3147 this->CurrentLocalGenerator, configName);
3148 if (xcconfig.empty()) {
3152 auto sf = this->CurrentMakefile->GetSource(xcconfig);
3154 cmSystemTools::Error(
3155 cmStrCat("sources for ALL_BUILD do not contain xcconfig file: '",
3156 xcconfig, "' (configuration: ", configName, ")"));
3160 cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
3161 sf->ResolveFullPath(), root->FindGeneratorTargetToUse("ALL_BUILD"), "",
3165 // error is already reported by CreateXCodeFileReferenceFromPath
3169 config->AddAttribute("baseConfigurationReference",
3170 this->CreateObjectReference(fileRef));
3173 void cmGlobalXCodeGenerator::CreateTargetXCConfigSettings(
3174 cmGeneratorTarget* target, cmXCodeObject* config,
3175 const std::string& configName)
3178 cmGeneratorExpression::Evaluate(target->GetSafeProperty("XCODE_XCCONFIG"),
3179 this->CurrentLocalGenerator, configName);
3180 if (xcconfig.empty()) {
3184 auto sf = target->Makefile->GetSource(xcconfig);
3186 cmSystemTools::Error(cmStrCat("target sources for target ",
3187 target->Target->GetName(),
3188 " do not contain xcconfig file: '", xcconfig,
3189 "' (configuration: ", configName, ")"));
3193 cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
3194 sf->ResolveFullPath(), target, "", sf);
3196 // error is already reported by CreateXCodeFileReferenceFromPath
3199 config->AddAttribute("baseConfigurationReference",
3200 this->CreateObjectReference(fileRef));
3203 const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
3204 cmGeneratorTarget const* target) const
3206 if (this->XcodeVersion >= 60 &&
3207 (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
3208 target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
3209 return "OTHER_LIBTOOLFLAGS";
3211 return "OTHER_LDFLAGS";
3214 const char* cmGlobalXCodeGenerator::GetTargetFileType(
3215 cmGeneratorTarget* target)
3217 if (cmValue e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
3221 switch (target->GetType()) {
3222 case cmStateEnums::OBJECT_LIBRARY:
3223 return "archive.ar";
3224 case cmStateEnums::STATIC_LIBRARY:
3225 return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
3227 case cmStateEnums::MODULE_LIBRARY:
3228 if (target->IsXCTestOnApple()) {
3229 return "wrapper.cfbundle";
3231 if (target->IsCFBundleOnApple()) {
3232 return "wrapper.plug-in";
3234 return "compiled.mach-o.executable";
3235 case cmStateEnums::SHARED_LIBRARY:
3236 return (target->GetPropertyAsBool("FRAMEWORK")
3237 ? "wrapper.framework"
3238 : "compiled.mach-o.dylib");
3239 case cmStateEnums::EXECUTABLE:
3240 return "compiled.mach-o.executable";
3247 const char* cmGlobalXCodeGenerator::GetTargetProductType(
3248 cmGeneratorTarget* target)
3250 if (cmValue e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
3254 switch (target->GetType()) {
3255 case cmStateEnums::OBJECT_LIBRARY:
3256 return "com.apple.product-type.library.static";
3257 case cmStateEnums::STATIC_LIBRARY:
3258 return (target->GetPropertyAsBool("FRAMEWORK")
3259 ? "com.apple.product-type.framework"
3260 : "com.apple.product-type.library.static");
3261 case cmStateEnums::MODULE_LIBRARY:
3262 if (target->IsXCTestOnApple()) {
3263 return "com.apple.product-type.bundle.unit-test";
3264 } else if (target->IsCFBundleOnApple()) {
3265 return "com.apple.product-type.bundle";
3267 return "com.apple.product-type.tool";
3269 case cmStateEnums::SHARED_LIBRARY:
3270 return (target->GetPropertyAsBool("FRAMEWORK")
3271 ? "com.apple.product-type.framework"
3272 : "com.apple.product-type.library.dynamic");
3273 case cmStateEnums::EXECUTABLE:
3274 return (target->GetPropertyAsBool("MACOSX_BUNDLE")
3275 ? "com.apple.product-type.application"
3276 : "com.apple.product-type.tool");
3283 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
3284 cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
3286 if (!gtgt->IsInBuildSystem()) {
3289 cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
3290 target->AddAttribute("buildPhases", buildPhases);
3291 cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3292 target->AddAttribute("buildRules", buildRules);
3293 std::string defConfig;
3294 defConfig = this->AddConfigurations(target, gtgt);
3295 cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3296 target->AddAttribute("dependencies", dependencies);
3297 target->AddAttribute("name", this->CreateString(gtgt->GetName()));
3298 target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
3300 cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
3301 if (const char* fileType = this->GetTargetFileType(gtgt)) {
3302 fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
3304 std::string fullName;
3305 if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
3306 fullName = cmStrCat("lib", gtgt->GetName(), ".a");
3308 fullName = gtgt->GetFullName(defConfig);
3310 fileRef->AddAttribute("path", this->CreateString(fullName));
3311 fileRef->AddAttribute("sourceTree",
3312 this->CreateString("BUILT_PRODUCTS_DIR"));
3313 fileRef->SetComment(gtgt->GetName());
3314 target->AddAttribute("productReference",
3315 this->CreateObjectReference(fileRef));
3316 if (const char* productType = this->GetTargetProductType(gtgt)) {
3317 target->AddAttribute("productType", this->CreateString(productType));
3319 target->SetTarget(gtgt);
3320 this->XCodeObjectMap[gtgt] = target;
3321 target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
3325 cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
3326 cmGeneratorTarget const* t)
3332 auto const i = this->XCodeObjectMap.find(t);
3333 if (i == this->XCodeObjectMap.end()) {
3339 std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
3340 cm::string_view key)
3342 std::string objectId;
3344 cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
3346 hash.Append(&ptype, sizeof(ptype));
3348 objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
3350 char cUuid[40] = { 0 };
3351 CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
3352 CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
3353 CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
3357 cmSystemTools::ReplaceString(objectId, "-", "");
3358 if (objectId.size() > 24) {
3359 objectId = objectId.substr(0, 24);
3365 std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
3366 const std::string& id)
3368 std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
3369 cmValue storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
3375 this->CMakeInstance->AddCacheEntry(
3376 guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
3381 void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
3382 cmXCodeObject* dependTarget)
3384 // This is called once for every edge in the target dependency graph.
3385 cmXCodeObject* container =
3386 this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
3387 container->SetComment("PBXContainerItemProxy");
3388 container->AddAttribute("containerPortal",
3389 this->CreateObjectReference(this->RootObject));
3390 container->AddAttribute("proxyType", this->CreateString("1"));
3391 container->AddAttribute("remoteGlobalIDString",
3392 this->CreateObjectReference(dependTarget));
3393 container->AddAttribute(
3394 "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
3395 cmXCodeObject* targetdep =
3396 this->CreateObject(cmXCodeObject::PBXTargetDependency);
3397 targetdep->SetComment("PBXTargetDependency");
3398 targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
3399 targetdep->AddAttribute("targetProxy",
3400 this->CreateObjectReference(container));
3402 cmXCodeObject* depends = target->GetAttribute("dependencies");
3404 cmSystemTools::Error(
3405 "target does not have dependencies attribute error..");
3408 depends->AddUniqueObject(targetdep);
3412 void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
3413 const char* attribute,
3414 cmXCodeObject* value)
3417 cmXCodeObject* attr = settings->GetAttribute(attribute);
3419 settings->AddAttribute(attribute, value);
3421 this->AppendBuildSettingAttribute(settings, attribute, attr, value);
3426 void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
3427 cmXCodeObject* settings, const char* attribute, cmXCodeObject* attr,
3428 cmXCodeObject* value)
3430 if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
3431 value->GetType() != cmXCodeObject::STRING) {
3432 cmSystemTools::Error("Unsupported value type for appending: " +
3433 std::string(attribute));
3436 if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
3437 if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
3438 for (auto* obj : value->GetObjectList()) {
3439 attr->AddObject(obj);
3442 attr->AddObject(value);
3444 } else if (attr->GetType() == cmXCodeObject::STRING) {
3445 if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
3446 // Add old value as a list item to new object list
3447 // and replace the attribute with the new list
3448 value->PrependObject(attr);
3449 settings->AddAttribute(attribute, value);
3451 std::string newValue =
3452 cmStrCat(attr->GetString(), ' ', value->GetString());
3453 attr->SetString(newValue);
3456 cmSystemTools::Error("Unsupported attribute type for appending: " +
3457 std::string(attribute));
3461 void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
3462 cmXCodeObject* target, const char* attribute, cmXCodeObject* value,
3463 const std::string& configName)
3465 // There are multiple configurations. Add the setting to the
3466 // buildSettings of the configuration name given.
3467 cmXCodeObject* configurationList =
3468 target->GetAttribute("buildConfigurationList")->GetObject();
3469 cmXCodeObject* buildConfigs =
3470 configurationList->GetAttribute("buildConfigurations");
3471 for (auto obj : buildConfigs->GetObjectList()) {
3472 if (configName.empty() ||
3473 obj->GetAttribute("name")->GetString() == configName) {
3474 cmXCodeObject* settings = obj->GetAttribute("buildSettings");
3475 this->AppendOrAddBuildSetting(settings, attribute, value);
3480 void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
3481 cmXCodeObject* target, const char* attribute)
3483 cmXCodeObject* configurationList =
3484 target->GetAttribute("buildConfigurationList")->GetObject();
3485 cmXCodeObject* buildConfigs =
3486 configurationList->GetAttribute("buildConfigurations");
3487 for (auto obj : buildConfigs->GetObjectList()) {
3488 cmXCodeObject* settings = obj->GetAttribute("buildSettings");
3489 if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
3490 BuildObjectListOrString inherited(this, true);
3491 inherited.Add("$(inherited)");
3492 this->AppendBuildSettingAttribute(settings, attribute, attr,
3493 inherited.CreateList());
3498 void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
3500 cmGeneratorTarget* gt = target->GetTarget();
3502 cmSystemTools::Error("Error no target on xobject\n");
3505 if (!gt->IsInBuildSystem()) {
3509 // Add dependencies on other CMake targets.
3510 for (const auto& dep : this->GetTargetDirectDepends(gt)) {
3511 if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
3512 this->AddDependTarget(target, dptarget);
3516 // Separate libraries into ones that can be linked using "Link Binary With
3517 // Libraries" build phase and the ones that can't. Only targets that build
3518 // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
3519 // this feature and only targets that represent actual libraries (object,
3520 // static, dynamic or bundle, excluding executables) will be used. These are
3521 // limitations imposed by CMake use-cases - otherwise a lot of things break.
3522 // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
3524 std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
3526 auto addToLinkerArguments =
3527 [&configItemMap](const std::string& configName,
3528 cmComputeLinkInformation::Item const* libItemPtr) {
3529 auto& linkVector = configItemMap[configName];
3530 if (std::find_if(linkVector.begin(), linkVector.end(),
3531 [libItemPtr](cmComputeLinkInformation::Item const* p) {
3532 return p == libItemPtr;
3533 }) == linkVector.end()) {
3534 linkVector.push_back(libItemPtr);
3537 std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
3538 std::map<std::string, std::vector<std::string>> targetConfigMap;
3539 using ConfigItemPair =
3540 std::pair<std::string, cmComputeLinkInformation::Item const*>;
3541 std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
3542 std::map<std::string, std::vector<std::string>> targetProductNameMap;
3543 bool useLinkPhase = false;
3544 bool forceLinkPhase = false;
3546 target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
3548 if (*prop == "BUILT_ONLY") {
3549 useLinkPhase = true;
3550 } else if (*prop == "KNOWN_LOCATION") {
3551 useLinkPhase = true;
3552 forceLinkPhase = true;
3553 } else if (*prop != "NONE") {
3554 cmSystemTools::Error("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: " +
3559 for (auto const& configName : this->CurrentConfigurationTypes) {
3560 cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
3564 for (auto const& libItem : cli->GetItems()) {
3565 // We want to put only static libraries, dynamic libraries, frameworks
3566 // and bundles that are built from targets that are not imported in "Link
3567 // Binary With Libraries" build phase. Except if the target property
3568 // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
3569 // non-target libraries will be added as well.
3571 (gt->GetType() == cmStateEnums::EXECUTABLE ||
3572 gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
3573 gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
3575 (!libItem.Target->IsImported() || forceLinkPhase) &&
3576 (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
3577 libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
3578 libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
3579 libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
3581 libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
3583 std::string libName;
3584 bool canUseLinkPhase = true;
3585 if (libItem.Target) {
3586 if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
3587 canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
3589 // If a library target uses custom build output directory Xcode
3590 // won't pick it up so we have to resort back to linker flags, but
3591 // that's OK as long as the custom output dir is absolute path.
3592 for (auto const& libConfigName : this->CurrentConfigurationTypes) {
3593 canUseLinkPhase = canUseLinkPhase &&
3594 libItem.Target->UsesDefaultOutputDir(
3595 libConfigName, cmStateEnums::RuntimeBinaryArtifact);
3598 libName = libItem.Target->GetName();
3600 libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
3601 // We don't want all the possible files here, just standard libraries
3602 const auto libExt = cmSystemTools::GetFilenameExtension(libName);
3603 if (!IsLinkPhaseLibraryExtension(libExt)) {
3604 canUseLinkPhase = false;
3607 if (canUseLinkPhase) {
3608 // Add unique configuration name to target-config map for later
3610 auto& configVector = targetConfigMap[libName];
3611 if (std::find(configVector.begin(), configVector.end(),
3612 configName) == configVector.end()) {
3613 configVector.push_back(configName);
3615 // Add a pair of config and item to target-item map
3616 auto& itemVector = targetItemMap[libName];
3617 itemVector.emplace_back(ConfigItemPair(configName, &libItem));
3618 // Add product file-name to a lib-product map
3620 cmSystemTools::GetFilenameName(libItem.Value.Value);
3621 auto& productVector = targetProductNameMap[libName];
3622 if (std::find(productVector.begin(), productVector.end(),
3623 productName) == productVector.end()) {
3624 productVector.push_back(productName);
3629 // Add this library item to a regular linker flag list
3630 addToLinkerArguments(configName, &libItem);
3634 // Go through target library map and separate libraries that are linked
3635 // in all configurations and produce only single product, from the rest.
3636 // Only these will be linked through "Link Binary With Libraries" build
3638 for (auto const& targetLibConfigs : targetConfigMap) {
3639 // Add this library to "Link Binary With Libraries" build phase if it's
3640 // linked in all configurations and it has only one product name
3641 auto& itemVector = targetItemMap[targetLibConfigs.first];
3642 auto& productVector = targetProductNameMap[targetLibConfigs.first];
3643 if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
3644 productVector.size() == 1) {
3645 // Add this library to "Link Binary With Libraries" list
3646 linkPhaseTargetVector.push_back(itemVector[0].second);
3648 for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
3649 // Add this library item to a regular linker flag list
3650 addToLinkerArguments(libItem.first, libItem.second);
3655 // Add libraries to "Link Binary With Libraries" build phase and collect
3656 // their search paths. Xcode does not support per-configuration linking
3657 // in this build phase so we don't have to do this for each configuration
3659 std::vector<std::string> linkSearchPaths;
3660 std::vector<std::string> frameworkSearchPaths;
3661 for (auto const& libItem : linkPhaseTargetVector) {
3662 // Add target output directory as a library search path
3663 std::string linkDir;
3664 if (libItem->Target) {
3665 linkDir = libItem->Target->GetLocationForBuild();
3667 linkDir = libItem->Value.Value;
3669 if (cmHasSuffix(libItem->GetFeatureName(), "FRAMEWORK"_s)) {
3670 auto fwDescriptor = this->SplitFrameworkPath(
3671 linkDir, cmGlobalGenerator::FrameworkFormat::Extended);
3672 if (fwDescriptor && !fwDescriptor->Directory.empty()) {
3673 linkDir = fwDescriptor->Directory;
3674 if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
3675 linkDir) == frameworkSearchPaths.end()) {
3676 frameworkSearchPaths.push_back(linkDir);
3680 linkDir = cmSystemTools::GetParentDirectory(linkDir);
3681 if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
3682 linkSearchPaths.end()) {
3683 linkSearchPaths.push_back(linkDir);
3687 if (libItem->Target && !libItem->Target->IsImported()) {
3688 for (auto const& configName : this->CurrentConfigurationTypes) {
3689 target->AddDependTarget(configName, libItem->Target->GetName());
3692 // Get the library target
3693 auto* libTarget = FindXCodeTarget(libItem->Target);
3694 cmXCodeObject* buildFile;
3696 if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
3697 // Get or create a direct file ref in the root project
3698 auto cleanPath = libItem->Value.Value;
3699 if (cmSystemTools::FileIsFullPath(cleanPath)) {
3700 // Some arguments are reported as paths, but they are actually not,
3701 // so we can't collapse them, and neither can we collapse relative
3703 cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
3705 auto it = this->ExternalLibRefs.find(cleanPath);
3706 if (it == this->ExternalLibRefs.end()) {
3707 buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
3709 // Add this library item back to a regular linker flag list
3710 for (const auto& conf : configItemMap) {
3711 addToLinkerArguments(conf.first, libItem);
3715 this->ExternalLibRefs.emplace(cleanPath, buildFile);
3717 buildFile = it->second;
3720 // Add this library item back to a regular linker flag list
3721 for (const auto& conf : configItemMap) {
3722 addToLinkerArguments(conf.first, libItem);
3727 // Add the target output file as a build reference for other targets
3729 auto* fileRefObject = libTarget->GetAttribute("productReference");
3730 if (!fileRefObject) {
3731 // Add this library item back to a regular linker flag list
3732 for (const auto& conf : configItemMap) {
3733 addToLinkerArguments(conf.first, libItem);
3737 auto it = FileRefToBuildFileMap.find(fileRefObject);
3738 if (it == FileRefToBuildFileMap.end()) {
3739 buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
3740 buildFile->AddAttribute("fileRef", fileRefObject);
3741 FileRefToBuildFileMap[fileRefObject] = buildFile;
3743 buildFile = it->second;
3746 // Add this reference to current target
3747 auto* buildPhases = target->GetAttribute("buildPhases");
3749 cmSystemTools::Error("Missing buildPhase of target");
3752 auto* frameworkBuildPhase =
3753 buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
3754 if (!frameworkBuildPhase) {
3755 cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
3758 auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
3760 cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
3763 if (buildFile && !buildFiles->HasObject(buildFile)) {
3764 buildFiles->AddObject(buildFile);
3768 // Loop over configuration types and set per-configuration info.
3769 for (auto const& configName : this->CurrentConfigurationTypes) {
3771 // Add object library contents as link flags.
3772 BuildObjectListOrString libSearchPaths(this, true);
3773 std::vector<cmSourceFile const*> objs;
3774 gt->GetExternalObjects(objs, configName);
3775 for (auto sourceFile : objs) {
3776 if (sourceFile->GetObjectLibrary().empty()) {
3779 libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
3781 this->AppendBuildSettingAttribute(
3782 target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
3786 // Skip link information for object libraries.
3787 if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
3788 gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
3792 // Compute the link library and directory information.
3793 cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
3798 // Add dependencies directly on library files.
3799 for (auto const& libDep : cli->GetDepends()) {
3800 target->AddDependLibrary(configName, libDep);
3803 // add the library search paths
3805 BuildObjectListOrString libSearchPaths(this, true);
3807 std::string linkDirs;
3808 for (auto const& libDir : cli->GetDirectories()) {
3809 if (!libDir.empty() && libDir != "/usr/lib") {
3810 cmPolicies::PolicyStatus cmp0142 =
3811 target->GetTarget()->GetPolicyStatusCMP0142();
3812 if (cmp0142 == cmPolicies::OLD || cmp0142 == cmPolicies::WARN) {
3813 libSearchPaths.Add(this->XCodeEscapePath(
3814 libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)"));
3816 libSearchPaths.Add(this->XCodeEscapePath(libDir));
3820 // Add previously collected paths where to look for libraries
3821 // that were added to "Link Binary With Libraries"
3822 for (auto& libDir : linkSearchPaths) {
3823 libSearchPaths.Add(this->XCodeEscapePath(libDir));
3825 if (!libSearchPaths.IsEmpty()) {
3826 this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
3827 libSearchPaths.CreateList(),
3832 // add framework search paths
3834 BuildObjectListOrString fwSearchPaths(this, true);
3835 // Add previously collected paths where to look for frameworks
3836 // that were added to "Link Binary With Libraries"
3837 for (auto& fwDir : frameworkSearchPaths) {
3838 fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
3840 if (!fwSearchPaths.IsEmpty()) {
3841 this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
3842 fwSearchPaths.CreateList(),
3847 // now add the left-over link libraries
3849 // Keep track of framework search paths we've already added or that are
3850 // part of the set of implicit search paths. We don't want to repeat
3851 // them and we also need to avoid hard-coding any SDK-specific paths.
3852 // This is essential for getting device-and-simulator builds to work,
3853 // otherwise we end up hard-coding a path to the wrong SDK for
3854 // SDK-provided frameworks that are added by their full path.
3855 std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
3856 const auto& fwPaths = cli->GetFrameworkPaths();
3857 emitted.insert(fwPaths.begin(), fwPaths.end());
3858 BuildObjectListOrString libPaths(this, true);
3859 BuildObjectListOrString fwSearchPaths(this, true);
3860 for (auto const& libItem : configItemMap[configName]) {
3861 auto const& libName = *libItem;
3862 if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
3863 auto cleanPath = libName.Value.Value;
3864 if (cmSystemTools::FileIsFullPath(cleanPath)) {
3865 cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
3868 cmHasSuffix(libName.GetFeatureName(), "FRAMEWORK"_s);
3870 const auto fwDescriptor = this->SplitFrameworkPath(
3871 cleanPath, cmGlobalGenerator::FrameworkFormat::Extended);
3872 if (!fwDescriptor->Directory.empty() &&
3873 emitted.insert(fwDescriptor->Directory).second) {
3874 // This is a search path we had not added before and it isn't
3875 // an implicit search path, so we need it
3877 this->XCodeEscapePath(fwDescriptor->Directory));
3879 if (libName.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s) {
3880 // use the full path
3882 libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
3885 libPaths.Add(libName
3886 .GetFormattedItem(this->XCodeEscapePath(
3887 fwDescriptor->GetLinkName()))
3892 libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
3895 if ((!libName.Target || libName.Target->IsImported()) &&
3896 (isFramework || IsLinkPhaseLibraryExtension(cleanPath))) {
3897 // Create file reference for embedding
3898 auto it = this->ExternalLibRefs.find(cleanPath);
3899 if (it == this->ExternalLibRefs.end()) {
3901 this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
3903 this->ExternalLibRefs.emplace(cleanPath, buildFile);
3907 } else if (!libName.Target ||
3908 libName.Target->GetType() !=
3909 cmStateEnums::INTERFACE_LIBRARY) {
3910 libPaths.Add(libName.Value.Value);
3912 if (libName.Target && !libName.Target->IsImported()) {
3913 target->AddDependTarget(configName, libName.Target->GetName());
3916 if (!libPaths.IsEmpty()) {
3917 this->AppendBuildSettingAttribute(target,
3918 this->GetTargetLinkFlagsVar(gt),
3919 libPaths.CreateList(), configName);
3921 if (!fwSearchPaths.IsEmpty()) {
3922 this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
3923 fwSearchPaths.CreateList(),
3930 void cmGlobalXCodeGenerator::AddEmbeddedObjects(
3931 cmXCodeObject* target, const std::string& copyFilesBuildPhaseName,
3932 const std::string& embedPropertyName, const std::string& dstSubfolderSpec,
3933 int actionsOnByDefault)
3935 cmGeneratorTarget* gt = target->GetTarget();
3937 cmSystemTools::Error("Error no target on xobject\n");
3940 if (!gt->IsInBuildSystem()) {
3943 bool isFrameworkTarget = gt->IsFrameworkOnApple();
3944 bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
3945 bool isCFBundleTarget = gt->IsCFBundleOnApple();
3946 if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
3949 cmValue files = gt->GetProperty(embedPropertyName);
3954 // Create an "Embedded Frameworks" build phase
3955 auto* copyFilesBuildPhase =
3956 this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
3957 copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
3958 copyFilesBuildPhase->AddAttribute("buildActionMask",
3959 this->CreateString("2147483647"));
3960 copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
3961 this->CreateString(dstSubfolderSpec));
3962 copyFilesBuildPhase->AddAttribute(
3963 "name", this->CreateString(copyFilesBuildPhaseName));
3964 if (cmValue fwEmbedPath =
3965 gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
3966 copyFilesBuildPhase->AddAttribute("dstPath",
3967 this->CreateString(*fwEmbedPath));
3969 copyFilesBuildPhase->AddAttribute("dstPath", this->CreateString(""));
3971 copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
3972 this->CreateString("0"));
3973 cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3974 // Collect all embedded frameworks and dylibs and add them to build phase
3975 std::vector<std::string> relFiles = cmExpandedList(*files);
3976 for (std::string const& relFile : relFiles) {
3977 cmXCodeObject* buildFile{ nullptr };
3978 std::string filePath = relFile;
3979 auto* genTarget = this->FindGeneratorTarget(relFile);
3981 // This is a target - get it's product path reference
3982 auto* xcTarget = this->FindXCodeTarget(genTarget);
3984 cmSystemTools::Error("Can not find a target for " +
3985 genTarget->GetName());
3988 // Add the target output file as a build reference for other targets
3990 auto* fileRefObject = xcTarget->GetAttribute("productReference");
3991 if (!fileRefObject) {
3992 cmSystemTools::Error("Target " + genTarget->GetName() +
3993 " is missing product reference");
3996 auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
3997 if (it == this->FileRefToEmbedBuildFileMap.end()) {
3998 buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
3999 buildFile->AddAttribute("fileRef", fileRefObject);
4000 this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
4002 buildFile = it->second;
4004 } else if (cmSystemTools::IsPathToFramework(relFile) ||
4005 cmSystemTools::IsPathToMacOSSharedLibrary(relFile)) {
4006 // This is a regular string path - create file reference
4007 auto it = this->EmbeddedLibRefs.find(relFile);
4008 if (it == this->EmbeddedLibRefs.end()) {
4009 cmXCodeObject* fileRef =
4010 this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
4012 buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
4013 buildFile->SetComment(fileRef->GetComment());
4014 buildFile->AddAttribute("fileRef",
4015 this->CreateObjectReference(fileRef));
4018 cmSystemTools::Error("Can't create build file for " + relFile);
4021 this->EmbeddedLibRefs.emplace(filePath, buildFile);
4023 buildFile = it->second;
4027 cmSystemTools::Error("Can't find a build file for " + relFile);
4030 // Set build file configuration
4031 cmXCodeObject* settings =
4032 this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4033 cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4035 bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
4036 if (auto prop = gt->GetProperty(
4037 cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
4038 removeHeaders = cmIsOn(*prop);
4040 if (removeHeaders) {
4041 attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
4044 bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
4046 gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
4047 codeSign = cmIsOn(*prop);
4050 attrs->AddObject(this->CreateString("CodeSignOnCopy"));
4053 settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
4054 buildFile->AddAttributeIfNotEmpty("settings", settings);
4055 if (!buildFiles->HasObject(buildFile)) {
4056 buildFiles->AddObject(buildFile);
4059 copyFilesBuildPhase->AddAttribute("files", buildFiles);
4060 auto* buildPhases = target->GetAttribute("buildPhases");
4061 // Embed-something build phases must be inserted before the post-build
4062 // command because that command is expected to be last
4063 buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
4064 copyFilesBuildPhase);
4067 void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
4069 static const auto dstSubfolderSpec = "10";
4071 // Despite the name, by default Xcode uses "Embed Frameworks" build phase
4072 // for both frameworks and dynamic libraries
4073 this->AddEmbeddedObjects(target, "Embed Frameworks",
4074 "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
4075 NoActionOnCopyByDefault);
4078 void cmGlobalXCodeGenerator::AddEmbeddedPlugIns(cmXCodeObject* target)
4080 static const auto dstSubfolderSpec = "13";
4082 this->AddEmbeddedObjects(target, "Embed PlugIns", "XCODE_EMBED_PLUGINS",
4083 dstSubfolderSpec, NoActionOnCopyByDefault);
4086 void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
4088 static const auto dstSubfolderSpec = "13";
4090 this->AddEmbeddedObjects(target, "Embed App Extensions",
4091 "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
4092 RemoveHeadersOnCopyByDefault);
4095 bool cmGlobalXCodeGenerator::CreateGroups(
4096 std::vector<cmLocalGenerator*>& generators)
4098 for (auto& generator : generators) {
4099 cmMakefile* mf = generator->GetMakefile();
4100 std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
4101 for (const auto& gtgt : generator->GetGeneratorTargets()) {
4102 // Same skipping logic here as in CreateXCodeTargets so that we do not
4103 // end up with (empty anyhow) ZERO_CHECK, install, or test source
4106 if (!gtgt->IsInBuildSystem() ||
4107 gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
4108 gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
4112 auto addSourceToGroup = [this, mf, >gt,
4113 &sourceGroups](std::string const& source) {
4114 cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
4115 cmXCodeObject* pbxgroup =
4116 this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
4117 std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
4118 this->GroupMap[key] = pbxgroup;
4121 // Put cmSourceFile instances in proper groups:
4122 for (auto const& si : gtgt->GetAllConfigSources()) {
4123 cmSourceFile const* sf = si.Source;
4124 if (!sf->GetObjectLibrary().empty()) {
4125 // Object library files go on the link line instead.
4128 addSourceToGroup(sf->GetFullPath());
4131 // Add CMakeLists.txt file for user convenience.
4133 std::string listfile =
4134 cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(),
4136 cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
4137 listfile, false, cmSourceFileLocationKind::Known);
4138 addSourceToGroup(sf->ResolveFullPath());
4141 // Add the Info.plist we are about to generate for an App Bundle.
4142 if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
4143 std::string plist = this->ComputeInfoPListLocation(gtgt.get());
4144 cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
4145 plist, true, cmSourceFileLocationKind::Known);
4146 addSourceToGroup(sf->ResolveFullPath());
4153 cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
4154 const std::string& name)
4156 cmXCodeObject* parentChildren = nullptr;
4158 parentChildren = parent->GetAttribute("children");
4160 cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
4161 cmXCodeObject* groupChildren =
4162 this->CreateObject(cmXCodeObject::OBJECT_LIST);
4163 group->AddAttribute("name", this->CreateString(name));
4164 group->AddAttribute("children", groupChildren);
4165 group->AddAttribute("sourceTree", this->CreateString("<group>"));
4166 if (parentChildren) {
4167 parentChildren->AddObject(group);
4172 cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
4173 cmGeneratorTarget* gtgt, cmSourceGroup* sg)
4177 const std::string targetFolder = gtgt->GetEffectiveFolderName();
4178 if (!targetFolder.empty()) {
4179 target = cmStrCat(targetFolder, '/');
4181 target += gtgt->GetName();
4182 s = cmStrCat(target, '/', sg->GetFullName());
4183 auto it = this->GroupNameMap.find(s);
4184 if (it != this->GroupNameMap.end()) {
4188 it = this->TargetGroup.find(target);
4189 cmXCodeObject* tgroup = nullptr;
4190 if (it != this->TargetGroup.end()) {
4191 tgroup = it->second;
4193 std::vector<std::string> tgt_folders = cmTokenize(target, "/");
4194 std::string curr_tgt_folder;
4195 for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
4198 curr_tgt_folder += "/";
4200 curr_tgt_folder += tgt_folders[i];
4201 it = this->TargetGroup.find(curr_tgt_folder);
4202 if (it != this->TargetGroup.end()) {
4203 tgroup = it->second;
4206 tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
4207 this->TargetGroup[curr_tgt_folder] = tgroup;
4209 this->MainGroupChildren->AddObject(tgroup);
4213 this->TargetGroup[target] = tgroup;
4215 // If it's the default source group (empty name) then put the source file
4216 // directly in the tgroup...
4218 if (sg->GetFullName().empty()) {
4219 this->GroupNameMap[s] = tgroup;
4223 // It's a recursive folder structure, let's find the real parent group
4224 if (sg->GetFullName() != sg->GetName()) {
4225 std::string curr_folder = cmStrCat(target, '/');
4226 for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) {
4227 curr_folder += folder;
4228 auto const i_folder = this->GroupNameMap.find(curr_folder);
4229 // Create new folder
4230 if (i_folder == this->GroupNameMap.end()) {
4231 cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
4232 this->GroupNameMap[curr_folder] = group;
4235 tgroup = i_folder->second;
4237 curr_folder += "\\";
4241 cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
4242 this->GroupNameMap[s] = group;
4246 bool cmGlobalXCodeGenerator::CreateXCodeObjects(
4247 cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
4249 this->ClearXCodeObjects();
4250 this->RootObject = nullptr;
4251 this->MainGroupChildren = nullptr;
4252 this->FrameworkGroup = nullptr;
4253 cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4254 group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
4255 cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4256 for (const std::string& CurrentConfigurationType :
4257 this->CurrentConfigurationTypes) {
4258 cmXCodeObject* buildStyle =
4259 this->CreateObject(cmXCodeObject::PBXBuildStyle);
4260 const std::string& name = CurrentConfigurationType;
4261 buildStyle->AddAttribute("name", this->CreateString(name));
4262 buildStyle->SetComment(name);
4263 cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4264 sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
4265 buildStyle->AddAttribute("buildSettings", sgroup);
4266 listObjs->AddObject(buildStyle);
4269 cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
4270 this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4271 mainGroup->AddAttribute("children", this->MainGroupChildren);
4272 mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
4274 // now create the cmake groups
4275 if (!this->CreateGroups(generators)) {
4279 cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
4280 productGroup->AddAttribute("name", this->CreateString("Products"));
4281 productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
4282 cmXCodeObject* productGroupChildren =
4283 this->CreateObject(cmXCodeObject::OBJECT_LIST);
4284 productGroup->AddAttribute("children", productGroupChildren);
4285 this->MainGroupChildren->AddObject(productGroup);
4287 this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
4288 this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
4289 this->FrameworkGroup->AddAttribute("sourceTree",
4290 this->CreateString("<group>"));
4291 cmXCodeObject* frameworkGroupChildren =
4292 this->CreateObject(cmXCodeObject::OBJECT_LIST);
4293 this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
4294 this->MainGroupChildren->AddObject(this->FrameworkGroup);
4296 this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
4297 this->RootObject->SetComment("Project object");
4299 std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
4300 this->RootObject->SetId(
4301 this->GetOrCreateId(project_id, this->RootObject->GetId()));
4303 group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4304 this->RootObject->AddAttribute("mainGroup",
4305 this->CreateObjectReference(mainGroup));
4306 this->RootObject->AddAttribute("buildSettings", group);
4307 this->RootObject->AddAttribute("buildStyles", listObjs);
4308 this->RootObject->AddAttribute("hasScannedForEncodings",
4309 this->CreateString("0"));
4310 group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4311 group->AddAttribute("BuildIndependentTargetsInParallel",
4312 this->CreateString("YES"));
4313 std::ostringstream v;
4314 v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
4315 group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
4316 this->RootObject->AddAttribute("attributes", group);
4317 this->RootObject->AddAttribute("compatibilityVersion",
4318 this->CreateString("Xcode 3.2"));
4319 // Point Xcode at the top of the source tree.
4322 this->RelativeToBinary(root->GetCurrentSourceDirectory());
4323 this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
4324 this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
4326 cmXCodeObject* configlist =
4327 this->CreateObject(cmXCodeObject::XCConfigurationList);
4328 cmXCodeObject* buildConfigurations =
4329 this->CreateObject(cmXCodeObject::OBJECT_LIST);
4330 using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
4332 std::string defaultConfigName;
4333 for (const auto& name : this->CurrentConfigurationTypes) {
4334 if (defaultConfigName.empty()) {
4335 defaultConfigName = name;
4337 cmXCodeObject* config =
4338 this->CreateObject(cmXCodeObject::XCBuildConfiguration);
4339 config->AddAttribute("name", this->CreateString(name));
4340 configs.push_back(std::make_pair(name, config));
4342 if (defaultConfigName.empty()) {
4343 defaultConfigName = "Debug";
4345 for (auto& config : configs) {
4346 buildConfigurations->AddObject(config.second);
4348 configlist->AddAttribute("buildConfigurations", buildConfigurations);
4350 std::string comment = cmStrCat("Build configuration list for PBXProject \"",
4351 this->CurrentProject, '"');
4352 configlist->SetComment(comment);
4353 configlist->AddAttribute("defaultConfigurationIsVisible",
4354 this->CreateString("0"));
4355 configlist->AddAttribute("defaultConfigurationName",
4356 this->CreateString(defaultConfigName));
4357 cmXCodeObject* buildSettings =
4358 this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4359 cmValue sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
4360 cmValue deploymentTarget =
4361 this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
4363 buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
4365 // recompute this as it may have been changed since enable language
4366 this->ComputeArchitectures(this->CurrentMakefile);
4367 std::string const archs = cmJoin(this->Architectures, " ");
4368 if (archs.empty()) {
4369 // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
4370 buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
4371 // When targeting macOS, use only the host architecture.
4372 if (this->SystemName == "Darwin"_s &&
4373 (!cmNonempty(sysroot) ||
4374 cmSystemTools::LowerCase(*sysroot).find("macos") !=
4375 std::string::npos)) {
4376 buildSettings->AddAttribute("ARCHS",
4377 this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
4380 // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
4381 buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
4383 if (cmNonempty(deploymentTarget)) {
4384 buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
4385 this->CreateString(*deploymentTarget));
4387 if (!this->GeneratorToolset.empty()) {
4388 buildSettings->AddAttribute("GCC_VERSION",
4389 this->CreateString(this->GeneratorToolset));
4391 if (this->GetLanguageEnabled("Swift")) {
4392 std::string swiftVersion;
4393 if (cmValue vers = this->CurrentMakefile->GetDefinition(
4394 "CMAKE_Swift_LANGUAGE_VERSION")) {
4395 swiftVersion = *vers;
4396 } else if (this->XcodeVersion >= 102) {
4397 swiftVersion = "4.0";
4398 } else if (this->XcodeVersion >= 83) {
4399 swiftVersion = "3.0";
4401 swiftVersion = "2.3";
4403 buildSettings->AddAttribute("SWIFT_VERSION",
4404 this->CreateString(swiftVersion));
4407 std::string const symroot = this->GetSymrootDir();
4408 buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
4410 // Inside a try_compile project, do not require signing on any platform.
4411 if (this->CMakeInstance->GetIsInTryCompile()) {
4412 buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
4413 this->CreateString("NO"));
4416 for (auto& config : configs) {
4417 CreateGlobalXCConfigSettings(root, config.second, config.first);
4419 cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
4421 // Put this last so it can override existing settings
4422 // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
4423 for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
4424 if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
4425 std::string attribute = var.substr(22);
4426 this->FilterConfigurationAttribute(config.first, attribute);
4427 if (!attribute.empty()) {
4428 std::string processed = cmGeneratorExpression::Evaluate(
4429 this->CurrentMakefile->GetSafeDefinition(var),
4430 this->CurrentLocalGenerator, config.first);
4431 buildSettingsForCfg->AddAttribute(attribute,
4432 this->CreateString(processed));
4436 // store per-config buildSettings into configuration object
4437 config.second->AddAttribute("buildSettings", buildSettingsForCfg);
4440 this->RootObject->AddAttribute("buildConfigurationList",
4441 this->CreateObjectReference(configlist));
4443 std::vector<cmXCodeObject*> targets;
4444 for (auto& generator : generators) {
4445 if (!this->CreateXCodeTargets(generator, targets)) {
4448 for (auto const& ccRoot : this->CustomCommandRoots) {
4449 if (ccRoot.second.size() > 1) {
4450 std::string e = "The custom command ";
4451 std::vector<std::string> const& outputs =
4452 ccRoot.first->GetCustomCommand()->GetOutputs();
4453 if (!outputs.empty()) {
4454 e = cmStrCat(e, "generating\n ", outputs[0]);
4456 e = cmStrCat(e, "driven by\n ", ccRoot.first->GetFullPath());
4458 e = cmStrCat(e, "\nis attached to multiple targets:");
4459 for (cmGeneratorTarget const* gt : ccRoot.second) {
4460 e = cmStrCat(e, "\n ", gt->GetName());
4464 "\nbut none of these is a common dependency of the other(s). "
4465 "This is not allowed by the Xcode \"new build system\".");
4466 generator->IssueMessage(MessageType::FATAL_ERROR, e);
4470 this->CustomCommandRoots.clear();
4472 // loop over all targets and add link and depend info
4473 for (auto t : targets) {
4474 this->AddDependAndLinkInformation(t);
4475 this->AddEmbeddedFrameworks(t);
4476 this->AddEmbeddedPlugIns(t);
4477 this->AddEmbeddedAppExtensions(t);
4478 // Inherit project-wide values for any target-specific search paths.
4479 this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
4480 this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
4481 this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
4482 this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
4483 this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
4484 this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
4485 this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
4486 this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
4487 this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
4490 if (this->XcodeBuildSystem == BuildSystem::One) {
4491 this->CreateXCodeDependHackMakefile(targets);
4493 // now add all targets to the root object
4494 cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4495 for (auto t : targets) {
4496 allTargets->AddObject(t);
4497 cmXCodeObject* productRef = t->GetAttribute("productReference");
4499 productGroupChildren->AddObject(productRef->GetObject());
4502 this->RootObject->AddAttribute("targets", allTargets);
4506 std::string cmGlobalXCodeGenerator::GetSymrootDir() const
4508 return cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/build");
4511 std::string cmGlobalXCodeGenerator::GetTargetTempDir(
4512 cmGeneratorTarget const* gt, std::string const& configName) const
4514 // Use a path inside the SYMROOT.
4515 return cmStrCat(this->GetSymrootDir(), '/', gt->GetName(), ".build/",
4519 void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
4521 this->Architectures.clear();
4522 cmValue sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT");
4524 mf->GetDefExpandList("CMAKE_OSX_ARCHITECTURES", this->Architectures);
4527 if (this->Architectures.empty()) {
4528 mf->GetDefExpandList("_CMAKE_APPLE_ARCHS_DEFAULT", this->Architectures);
4531 if (this->Architectures.empty()) {
4532 // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
4533 // platform-specific default ARCHS placeholder value.
4534 // Look up the arch that Xcode chooses in this case.
4535 if (cmValue arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
4536 this->ObjectDirArchDefault = *arch;
4537 // We expect only one arch but choose the first just in case.
4538 std::string::size_type pos = this->ObjectDirArchDefault.find(';');
4539 if (pos != std::string::npos) {
4540 this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
4545 this->ComputeObjectDirArch(mf);
4548 void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
4550 if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
4551 this->ObjectDirArch = "$(CURRENT_ARCH)";
4552 } else if (!this->Architectures.empty()) {
4553 this->ObjectDirArch = this->Architectures[0];
4555 this->ObjectDirArch = this->ObjectDirArchDefault;
4559 void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
4560 std::vector<cmXCodeObject*>& targets)
4562 cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
4563 if (!makefileStream) {
4564 cmSystemTools::Error("Could not create " + this->CurrentXCodeHackMakefile);
4567 makefileStream.SetCopyIfDifferent(true);
4568 // one more pass for external depend information not handled
4569 // correctly by xcode
4570 /* clang-format off */
4571 makefileStream << "# DO NOT EDIT\n";
4572 makefileStream << "# This makefile makes sure all linkable targets are\n";
4573 makefileStream << "# up-to-date with anything they link to\n"
4575 "\techo \"Do not invoke directly\"\n"
4577 /* clang-format on */
4579 std::set<std::string> dummyRules;
4581 // Write rules to help Xcode relink things at the right time.
4582 /* clang-format off */
4584 "# Rules to remove targets that are older than anything to which they\n"
4585 "# link. This forces Xcode to relink the targets from scratch. It\n"
4586 "# does not seem to check these dependencies itself.\n";
4587 /* clang-format on */
4588 for (const auto& configName : this->CurrentConfigurationTypes) {
4589 for (auto target : targets) {
4590 cmGeneratorTarget* gt = target->GetTarget();
4592 if (gt->GetType() == cmStateEnums::EXECUTABLE ||
4593 gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
4594 gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
4595 gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
4596 gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
4597 // Declare an entry point for the target post-build phase.
4598 makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
4602 if (gt->GetType() == cmStateEnums::EXECUTABLE ||
4603 gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
4604 gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
4605 gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
4606 std::string tfull = gt->GetFullPath(configName);
4607 std::string trel = this->ConvertToRelativeForMake(tfull);
4609 // Add this target to the post-build phases of its dependencies.
4610 auto const y = target->GetDependTargets().find(configName);
4611 if (y != target->GetDependTargets().end()) {
4612 for (auto const& deptgt : y->second) {
4613 makefileStream << this->PostBuildMakeTarget(deptgt, configName)
4614 << ": " << trel << "\n";
4618 std::vector<cmGeneratorTarget*> objlibs;
4619 gt->GetObjectLibrariesCMP0026(objlibs);
4620 for (auto objLib : objlibs) {
4621 makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
4623 << ": " << trel << "\n";
4626 // Create a rule for this target.
4627 makefileStream << trel << ":";
4629 // List dependencies if any exist.
4630 auto const x = target->GetDependLibraries().find(configName);
4631 if (x != target->GetDependLibraries().end()) {
4632 for (auto const& deplib : x->second) {
4633 std::string file = this->ConvertToRelativeForMake(deplib);
4634 makefileStream << "\\\n\t" << file;
4635 dummyRules.insert(file);
4639 for (auto objLib : objlibs) {
4641 const std::string objLibName = objLib->GetName();
4642 std::string d = cmStrCat(this->GetTargetTempDir(gt, configName),
4643 "/lib", objLibName, ".a");
4645 std::string dependency = this->ConvertToRelativeForMake(d);
4646 makefileStream << "\\\n\t" << dependency;
4647 dummyRules.insert(dependency);
4650 // Write the action to remove the target if it is out of date.
4651 makefileStream << "\n";
4652 makefileStream << "\t/bin/rm -f "
4653 << this->ConvertToRelativeForMake(tfull) << "\n";
4654 // if building for more than one architecture
4655 // then remove those executables as well
4656 if (this->Architectures.size() > 1) {
4657 std::string universal =
4658 cmStrCat(this->GetTargetTempDir(gt, configName), "/$(OBJDIR)/");
4659 for (const auto& architecture : this->Architectures) {
4660 std::string universalFile = cmStrCat(universal, architecture, '/',
4661 gt->GetFullName(configName));
4662 makefileStream << "\t/bin/rm -f "
4663 << this->ConvertToRelativeForMake(universalFile)
4667 makefileStream << "\n\n";
4672 makefileStream << "\n\n"
4673 << "# For each target create a dummy rule"
4674 << "so the target does not have to exist\n";
4675 for (auto const& dummyRule : dummyRules) {
4676 makefileStream << dummyRule << ":\n";
4680 void cmGlobalXCodeGenerator::OutputXCodeProject(
4681 cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
4683 if (generators.empty()) {
4686 if (!this->CreateXCodeObjects(root, generators)) {
4689 std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
4690 root->GetProjectName(), ".xcodeproj");
4691 cmSystemTools::MakeDirectory(xcodeDir);
4692 std::string xcodeProjFile = xcodeDir + "/project.pbxproj";
4693 cmGeneratedFileStream fout(xcodeProjFile);
4694 fout.SetCopyIfDifferent(true);
4698 this->WriteXCodePBXProj(fout, root, generators);
4700 bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
4701 this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
4703 this->ClearXCodeObjects();
4705 // Since this call may have created new cache entries, save the cache:
4707 root->GetMakefile()->GetCMakeInstance()->SaveCache(
4708 root->GetBinaryDirectory());
4711 bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
4712 const std::string& xcProjDir, cmLocalGenerator* root)
4714 // collect all tests for the targets
4715 std::map<std::string, cmXCodeScheme::TestObjects> testables;
4717 for (const auto& obj : this->XCodeObjects) {
4718 if (obj->GetType() != cmXCodeObject::OBJECT ||
4719 obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
4723 if (!obj->GetTarget()->IsXCTestOnApple()) {
4727 cmValue testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
4732 testables[*testee].push_back(obj.get());
4738 // Since the lowest available Xcode version for testing was 6.4,
4739 // I'm setting this as a limit then
4740 if (this->XcodeVersion >= 64) {
4741 for (const auto& obj : this->XCodeObjects) {
4742 if (obj->GetType() == cmXCodeObject::OBJECT &&
4743 (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
4744 obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
4745 (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
4746 obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
4747 const std::string& targetName = obj->GetTarget()->GetName();
4748 cmXCodeScheme schm(root, obj.get(), testables[targetName],
4749 this->CurrentConfigurationTypes,
4750 this->XcodeVersion);
4751 schm.WriteXCodeSharedScheme(xcProjDir,
4752 this->RelativeToSource(xcProjDir));
4761 void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
4762 const std::string& xcProjDir, bool hasGeneratedSchemes)
4764 std::string xcodeSharedDataDir =
4765 cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
4766 cmSystemTools::MakeDirectory(xcodeSharedDataDir);
4768 std::string workspaceSettingsFile =
4769 cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
4771 cmGeneratedFileStream fout(workspaceSettingsFile);
4772 fout.SetCopyIfDifferent(true);
4777 cmXMLWriter xout(fout);
4778 xout.StartDocument();
4779 xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
4780 "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
4781 xout.StartElement("plist");
4782 xout.Attribute("version", "1.0");
4783 xout.StartElement("dict");
4784 if (this->XcodeVersion >= 100) {
4785 xout.Element("key", "BuildSystemType");
4786 switch (this->XcodeBuildSystem) {
4787 case BuildSystem::One:
4788 xout.Element("string", "Original");
4789 if (this->XcodeVersion >= 130) {
4790 xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
4792 xout.Element("key", "DisableBuildSystemDeprecationWarning");
4794 xout.Element("true");
4796 case BuildSystem::Twelve:
4797 xout.Element("string", "Latest");
4801 if (hasGeneratedSchemes) {
4803 "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
4804 xout.Element("false");
4806 xout.EndElement(); // dict
4807 xout.EndElement(); // plist
4811 void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
4813 std::vector<cmLocalGenerator*>&)
4817 fout << "// !$*UTF8*$!\n";
4819 cmXCodeObject::Indent(1, fout);
4820 fout << "archiveVersion = 1;\n";
4821 cmXCodeObject::Indent(1, fout);
4822 fout << "classes = {\n";
4823 cmXCodeObject::Indent(1, fout);
4825 cmXCodeObject::Indent(1, fout);
4826 fout << "objectVersion = 46;\n";
4827 cmXCode21Object::PrintList(this->XCodeObjects, fout);
4828 cmXCodeObject::Indent(1, fout);
4829 fout << "rootObject = " << this->RootObject->GetId()
4830 << " /* Project object */;\n";
4834 const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
4836 return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
4839 std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
4840 const std::string& str, const std::string& config) const
4842 std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
4843 std::string replace2 = "$(CONFIGURATION)";
4845 std::string tmp = str;
4846 for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
4847 i = tmp.find(replace1, i)) {
4848 tmp.replace(i, replace1.size(), config);
4851 for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
4852 i = tmp.find(replace2, i)) {
4853 tmp.replace(i, replace2.size(), config);
4859 void cmGlobalXCodeGenerator::GetDocumentation(cmDocumentationEntry& entry)
4861 entry.Name = cmGlobalXCodeGenerator::GetActualName();
4862 entry.Brief = "Generate Xcode project files.";
4865 std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
4866 std::string const& p)
4868 return cmSystemTools::ConvertToOutputPath(p);
4871 std::string cmGlobalXCodeGenerator::RelativeToSource(const std::string& p)
4873 std::string const& rootSrc =
4874 this->CurrentRootGenerator->GetCurrentSourceDirectory();
4875 if (cmSystemTools::IsSubDirectory(p, rootSrc)) {
4876 return cmSystemTools::ForceToRelativePath(rootSrc, p);
4881 std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p)
4883 return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
4886 std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
4888 if (p.find_first_of(" []") != std::string::npos) {
4889 std::string t = cmStrCat('"', p, '"');
4895 void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
4896 const std::string& prefix, const std::string& config,
4897 const std::string& suffix, std::string& dir)
4899 if (!config.empty()) {
4906 std::string cmGlobalXCodeGenerator::LookupFlags(
4907 const std::string& varNamePrefix, const std::string& varNameLang,
4908 const std::string& varNameSuffix, const std::string& default_flags)
4910 if (!varNameLang.empty()) {
4911 std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
4912 if (cmValue varValue = this->CurrentMakefile->GetDefinition(varName)) {
4913 if (!varValue->empty()) {
4918 return default_flags;
4921 void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
4922 const char* defines_list,
4925 // Skip this if there are no definitions.
4926 if (!defines_list) {
4930 // Expand the list of definitions.
4931 std::vector<std::string> defines = cmExpandedList(defines_list);
4933 // Store the definitions in the string.
4934 this->AppendDefines(defs, defines, dflag);
4937 void cmGlobalXCodeGenerator::AppendDefines(
4938 BuildObjectListOrString& defs, std::vector<std::string> const& defines,
4941 // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
4943 for (auto const& define : defines) {
4944 // Start with -D if requested.
4945 def = cmStrCat(dflag ? "-D" : "", define);
4947 // Append the flag with needed escapes.
4949 this->AppendFlag(tmp, def);
4954 void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
4955 std::string const& flag) const
4957 // Short-circuit for an empty flag.
4962 // Separate from previous flags.
4963 if (!flags.empty()) {
4967 // Check if the flag needs quoting.
4969 flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
4971 // We escape a flag as follows:
4972 // - Place each flag in single quotes ''
4973 // - Escape a single quote as \'
4974 // - Escape a backslash as \\ since it itself is an escape
4975 // Note that in the code below we need one more level of escapes for
4976 // C string syntax in this source file.
4978 // The final level of escaping is done when the string is stored
4979 // into the project file by cmXCodeObject::PrintString.
4982 // Open single quote.
4986 // Flag value with escaped quotes and backslashes.
4987 for (auto c : flag) {
4990 } else if (c == '\\') {
4998 // Close single quote.
5003 std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
5004 cmGeneratorTarget* target)
5007 cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
5008 "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
5012 // Return true if the generated build tree may contain multiple builds.
5013 // i.e. "Can I build Debug and Release in the same tree?"
5014 bool cmGlobalXCodeGenerator::IsMultiConfig() const
5016 // Newer Xcode versions are multi config:
5020 bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
5021 cmTarget const& target, std::string* reason) const
5023 auto objectDirArch = GetTargetObjectDirArch(target, this->ObjectDirArch);
5025 if (objectDirArch.find('$') != std::string::npos) {
5026 if (reason != nullptr) {
5027 *reason = " under Xcode with multiple architectures";
5034 bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
5036 cmValue epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
5037 "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
5040 return mf->PlatformIsAppleEmbedded();
5043 return cmIsOn(*epnValue);
5046 bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
5048 // Xcode determines Resource location itself
5052 void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
5053 cmGeneratorTarget* gt) const
5055 auto objectDirArch = GetTargetObjectDirArch(*gt, this->ObjectDirArch);
5056 gt->ObjectDirectory =
5057 cmStrCat(this->GetTargetTempDir(gt, this->GetCMakeCFGIntDir()),
5058 "/$(OBJECT_FILE_DIR_normal:base)/", objectDirArch, '/');
5061 std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
5063 switch (mf->GetAppleSDKType()) {
5064 case cmMakefile::AppleSDK::AppleTVOS:
5065 case cmMakefile::AppleSDK::AppleTVSimulator:
5066 return "TVOS_DEPLOYMENT_TARGET";
5068 case cmMakefile::AppleSDK::IPhoneOS:
5069 case cmMakefile::AppleSDK::IPhoneSimulator:
5070 return "IPHONEOS_DEPLOYMENT_TARGET";
5072 case cmMakefile::AppleSDK::WatchOS:
5073 case cmMakefile::AppleSDK::WatchSimulator:
5074 return "WATCHOS_DEPLOYMENT_TARGET";
5076 case cmMakefile::AppleSDK::MacOS:
5078 return "MACOSX_DEPLOYMENT_TARGET";