The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1087 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #pragma once
  19. //==============================================================================
  20. class MakefileProjectExporter : public ProjectExporter
  21. {
  22. protected:
  23. //==============================================================================
  24. class MakeBuildConfiguration : public BuildConfiguration
  25. {
  26. public:
  27. MakeBuildConfiguration (Project& p, const ValueTree& settings, const ProjectExporter& e)
  28. : BuildConfiguration (p, settings, e),
  29. architectureTypeValue (config, Ids::linuxArchitecture, getUndoManager(), String()),
  30. pluginBinaryCopyStepValue (config, Ids::enablePluginBinaryCopyStep, getUndoManager(), true),
  31. vstBinaryLocation (config, Ids::vstBinaryLocation, getUndoManager(), "$(HOME)/.vst"),
  32. vst3BinaryLocation (config, Ids::vst3BinaryLocation, getUndoManager(), "$(HOME)/.vst3"),
  33. lv2BinaryLocation (config, Ids::lv2BinaryLocation, getUndoManager(), "$(HOME)/.lv2"),
  34. unityPluginBinaryLocation (config, Ids::unityPluginBinaryLocation, getUndoManager(), "$(HOME)/UnityPlugins")
  35. {
  36. linkTimeOptimisationValue.setDefault (false);
  37. optimisationLevelValue.setDefault (isDebug() ? gccO0 : gccO3);
  38. }
  39. void createConfigProperties (PropertyListBuilder& props) override
  40. {
  41. addRecommendedLinuxCompilerWarningsProperty (props);
  42. addGCCOptimisationProperty (props);
  43. props.add (new ChoicePropertyComponent (architectureTypeValue, "Architecture",
  44. { "<None>", "Native", "32-bit (-m32)", "64-bit (-m64)", "ARM v6", "ARM v7", "ARM v8-a" },
  45. { { String() }, "-march=native", "-m32", "-m64", "-march=armv6", "-march=armv7", "-march=armv8-a" }),
  46. "Specifies the 32/64-bit architecture to use. If you don't see the required architecture in this list, you can also specify the desired "
  47. "flag on the command-line when invoking make by passing \"TARGET_ARCH=-march=<arch to use>\"");
  48. auto isBuildingAnyPlugins = (project.shouldBuildVST() || project.shouldBuildVST3() || project.shouldBuildUnityPlugin() || project.shouldBuildLV2());
  49. if (isBuildingAnyPlugins)
  50. {
  51. props.add (new ChoicePropertyComponent (pluginBinaryCopyStepValue, "Enable Plugin Copy Step"),
  52. "Enable this to copy plugin binaries to a specified folder after building.");
  53. if (project.shouldBuildVST3())
  54. props.add (new TextPropertyComponentWithEnablement (vst3BinaryLocation, pluginBinaryCopyStepValue, "VST3 Binary Location",
  55. 1024, false),
  56. "The folder in which the compiled VST3 binary should be placed.");
  57. if (project.shouldBuildLV2())
  58. props.add (new TextPropertyComponentWithEnablement (lv2BinaryLocation, pluginBinaryCopyStepValue, "LV2 Binary Location",
  59. 1024, false),
  60. "The folder in which the compiled LV2 binary should be placed.");
  61. if (project.shouldBuildUnityPlugin())
  62. props.add (new TextPropertyComponentWithEnablement (unityPluginBinaryLocation, pluginBinaryCopyStepValue, "Unity Binary Location",
  63. 1024, false),
  64. "The folder in which the compiled Unity plugin binary and associated C# GUI script should be placed.");
  65. if (project.shouldBuildVST())
  66. props.add (new TextPropertyComponentWithEnablement (vstBinaryLocation, pluginBinaryCopyStepValue, "VST (Legacy) Binary Location",
  67. 1024, false),
  68. "The folder in which the compiled legacy VST binary should be placed.");
  69. }
  70. }
  71. String getModuleLibraryArchName() const override
  72. {
  73. auto archFlag = getArchitectureTypeString();
  74. String prefix ("-march=");
  75. if (archFlag.startsWith (prefix))
  76. return archFlag.substring (prefix.length());
  77. if (archFlag == "-m64")
  78. return "x86_64";
  79. if (archFlag == "-m32")
  80. return "i386";
  81. return "${JUCE_ARCH_LABEL}";
  82. }
  83. String getArchitectureTypeString() const { return architectureTypeValue.get(); }
  84. bool isPluginBinaryCopyStepEnabled() const { return pluginBinaryCopyStepValue.get(); }
  85. String getVSTBinaryLocationString() const { return vstBinaryLocation.get(); }
  86. String getVST3BinaryLocationString() const { return vst3BinaryLocation.get(); }
  87. String getLV2BinaryLocationString() const { return lv2BinaryLocation.get(); }
  88. String getUnityPluginBinaryLocationString() const { return unityPluginBinaryLocation.get(); }
  89. private:
  90. //==============================================================================
  91. ValueTreePropertyWithDefault architectureTypeValue, pluginBinaryCopyStepValue,
  92. vstBinaryLocation, vst3BinaryLocation, lv2BinaryLocation, unityPluginBinaryLocation;
  93. };
  94. BuildConfiguration::Ptr createBuildConfig (const ValueTree& tree) const override
  95. {
  96. return *new MakeBuildConfiguration (project, tree, *this);
  97. }
  98. public:
  99. //==============================================================================
  100. class MakefileTarget : public build_tools::ProjectType::Target
  101. {
  102. public:
  103. MakefileTarget (build_tools::ProjectType::Target::Type targetType, const MakefileProjectExporter& exporter)
  104. : build_tools::ProjectType::Target (targetType), owner (exporter)
  105. {}
  106. StringArray getCompilerFlags() const
  107. {
  108. StringArray result;
  109. if (getTargetFileType() == sharedLibraryOrDLL || getTargetFileType() == pluginBundle)
  110. {
  111. result.add ("-fPIC");
  112. result.add ("-fvisibility=hidden");
  113. }
  114. return result;
  115. }
  116. StringArray getLinkerFlags() const
  117. {
  118. StringArray result;
  119. if (getTargetFileType() == sharedLibraryOrDLL || getTargetFileType() == pluginBundle)
  120. {
  121. result.add ("-shared");
  122. if (getTargetFileType() == pluginBundle)
  123. result.add ("-Wl,--no-undefined");
  124. }
  125. return result;
  126. }
  127. StringPairArray getDefines (const BuildConfiguration& config) const
  128. {
  129. StringPairArray result;
  130. auto commonOptionKeys = owner.getAllPreprocessorDefs (config, build_tools::ProjectType::Target::unspecified).getAllKeys();
  131. auto targetSpecific = owner.getAllPreprocessorDefs (config, type);
  132. for (auto& key : targetSpecific.getAllKeys())
  133. if (! commonOptionKeys.contains (key))
  134. result.set (key, targetSpecific[key]);
  135. return result;
  136. }
  137. StringArray getTargetSettings (const MakeBuildConfiguration& config) const
  138. {
  139. if (type == AggregateTarget) // the aggregate target should not specify any settings at all!
  140. return {}; // it just defines dependencies on the other targets.
  141. StringArray s;
  142. auto cppflagsVarName = "JUCE_CPPFLAGS_" + getTargetVarName();
  143. s.add (cppflagsVarName + " := " + createGCCPreprocessorFlags (getDefines (config)));
  144. auto cflags = getCompilerFlags();
  145. if (! cflags.isEmpty())
  146. s.add ("JUCE_CFLAGS_" + getTargetVarName() + " := " + cflags.joinIntoString (" "));
  147. auto ldflags = getLinkerFlags();
  148. if (! ldflags.isEmpty())
  149. s.add ("JUCE_LDFLAGS_" + getTargetVarName() + " := " + ldflags.joinIntoString (" "));
  150. auto targetName = owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString (type == UnityPlugIn));
  151. if (owner.projectType.isStaticLibrary())
  152. targetName = getStaticLibbedFilename (targetName);
  153. else if (owner.projectType.isDynamicLibrary())
  154. targetName = getDynamicLibbedFilename (targetName);
  155. else
  156. targetName = targetName.upToLastOccurrenceOf (".", false, false) + getTargetFileSuffix();
  157. if (type == VST3PlugIn)
  158. {
  159. s.add ("JUCE_VST3DIR := " + escapeQuotesAndSpaces (targetName).upToLastOccurrenceOf (".", false, false) + ".vst3");
  160. s.add ("VST3_PLATFORM_ARCH := $(shell $(CXX) make_helpers/arch_detection.cpp 2>&1 | tr '\\n' ' ' | sed \"s/.*JUCE_ARCH \\([a-zA-Z0-9_-]*\\).*/\\1/\")");
  161. s.add ("JUCE_VST3SUBDIR := Contents/$(VST3_PLATFORM_ARCH)-linux");
  162. targetName = "$(JUCE_VST3DIR)/$(JUCE_VST3SUBDIR)/" + targetName;
  163. }
  164. else if (type == UnityPlugIn)
  165. {
  166. s.add ("JUCE_UNITYDIR := Unity");
  167. targetName = "$(JUCE_UNITYDIR)/" + targetName;
  168. }
  169. else if (type == LV2PlugIn)
  170. {
  171. s.add ("JUCE_LV2DIR := " + targetName + ".lv2");
  172. targetName = "$(JUCE_LV2DIR)/" + targetName + ".so";
  173. }
  174. else if (type == LV2TurtleProgram)
  175. {
  176. targetName = Project::getLV2FileWriterName();
  177. }
  178. s.add ("JUCE_TARGET_" + getTargetVarName() + String (" := ") + escapeQuotesAndSpaces (targetName));
  179. if (config.isPluginBinaryCopyStepEnabled()
  180. && (type == VST3PlugIn || type == VSTPlugIn || type == UnityPlugIn || type == LV2PlugIn))
  181. {
  182. String copyCmd ("JUCE_COPYCMD_" + getTargetVarName() + String (" := $(JUCE_OUTDIR)/"));
  183. if (type == VST3PlugIn)
  184. {
  185. s.add ("JUCE_VST3DESTDIR := " + config.getVST3BinaryLocationString());
  186. s.add (copyCmd + "$(JUCE_VST3DIR) $(JUCE_VST3DESTDIR)");
  187. }
  188. else if (type == VSTPlugIn)
  189. {
  190. s.add ("JUCE_VSTDESTDIR := " + config.getVSTBinaryLocationString());
  191. s.add (copyCmd + escapeQuotesAndSpaces (targetName) + " $(JUCE_VSTDESTDIR)");
  192. }
  193. else if (type == UnityPlugIn)
  194. {
  195. s.add ("JUCE_UNITYDESTDIR := " + config.getUnityPluginBinaryLocationString());
  196. s.add (copyCmd + "$(JUCE_UNITYDIR)/. $(JUCE_UNITYDESTDIR)");
  197. }
  198. else if (type == LV2PlugIn)
  199. {
  200. s.add ("JUCE_LV2DESTDIR := " + config.getLV2BinaryLocationString());
  201. s.add ("JUCE_LV2_FULL_PATH := $(JUCE_OUTDIR)/$(JUCE_TARGET_LV2_PLUGIN)");
  202. s.add (copyCmd + "$(JUCE_LV2DIR) $(JUCE_LV2DESTDIR)");
  203. }
  204. }
  205. return s;
  206. }
  207. String getTargetFileSuffix() const
  208. {
  209. if (type == VSTPlugIn || type == VST3PlugIn || type == UnityPlugIn || type == DynamicLibrary)
  210. return ".so";
  211. if (type == SharedCodeTarget || type == StaticLibrary)
  212. return ".a";
  213. return {};
  214. }
  215. String getTargetVarName() const
  216. {
  217. return String (getName()).toUpperCase().replaceCharacter (L' ', L'_');
  218. }
  219. void writeObjects (OutputStream& out, const Array<std::pair<File, String>>& filesToCompile) const
  220. {
  221. out << "OBJECTS_" + getTargetVarName() + String (" := \\") << newLine;
  222. for (auto& f : filesToCompile)
  223. out << " $(JUCE_OBJDIR)/" << escapeQuotesAndSpaces (owner.getObjectFileFor ({ f.first, owner.getTargetFolder(), build_tools::RelativePath::buildTargetFolder }))
  224. << " \\" << newLine;
  225. out << newLine;
  226. }
  227. void addFiles (OutputStream& out, const Array<std::pair<File, String>>& filesToCompile)
  228. {
  229. auto cppflagsVarName = "JUCE_CPPFLAGS_" + getTargetVarName();
  230. auto cflagsVarName = "JUCE_CFLAGS_" + getTargetVarName();
  231. for (auto& f : filesToCompile)
  232. {
  233. build_tools::RelativePath relativePath (f.first, owner.getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
  234. out << "$(JUCE_OBJDIR)/" << escapeQuotesAndSpaces (owner.getObjectFileFor (relativePath)) << ": " << escapeQuotesAndSpaces (relativePath.toUnixStyle()) << newLine
  235. << "\t-$(V_AT)mkdir -p $(JUCE_OBJDIR)" << newLine
  236. << "\t@echo \"Compiling " << relativePath.getFileName() << "\"" << newLine
  237. << (relativePath.hasFileExtension ("c;s;S") ? "\t$(V_AT)$(CC) $(JUCE_CFLAGS) " : "\t$(V_AT)$(CXX) $(JUCE_CXXFLAGS) ")
  238. << "$(" << cppflagsVarName << ") $(" << cflagsVarName << ")"
  239. << (f.second.isNotEmpty() ? " $(" + owner.getCompilerFlagSchemeVariableName (f.second) + ")" : "") << " -o \"$@\" -c \"$<\"" << newLine
  240. << newLine;
  241. }
  242. }
  243. String getBuildProduct() const
  244. {
  245. return "$(JUCE_OUTDIR)/$(JUCE_TARGET_" + getTargetVarName() + ")";
  246. }
  247. String getPhonyName() const
  248. {
  249. if (type == LV2TurtleProgram)
  250. return "LV2_MANIFEST_HELPER";
  251. return String (getName()).upToFirstOccurrenceOf (" ", false, false);
  252. }
  253. void writeTargetLine (OutputStream& out, const StringArray& packages)
  254. {
  255. jassert (type != AggregateTarget);
  256. out << getBuildProduct() << " : "
  257. << "$(OBJECTS_" << getTargetVarName() << ") $(RESOURCES)";
  258. if (type != SharedCodeTarget && owner.shouldBuildTargetType (SharedCodeTarget))
  259. out << " $(JUCE_OUTDIR)/$(JUCE_TARGET_SHARED_CODE)";
  260. if (type == LV2PlugIn)
  261. out << " $(JUCE_OUTDIR)/$(JUCE_TARGET_LV2_MANIFEST_HELPER)";
  262. out << newLine;
  263. if (! packages.isEmpty())
  264. {
  265. out << "\t@command -v $(PKG_CONFIG) >/dev/null 2>&1 || { echo >&2 \"pkg-config not installed. Please, install it.\"; exit 1; }" << newLine
  266. << "\t@$(PKG_CONFIG) --print-errors";
  267. for (auto& pkg : packages)
  268. out << " " << pkg;
  269. out << newLine;
  270. }
  271. out << "\t@echo Linking \"" << owner.projectName << " - " << getName() << "\"" << newLine
  272. << "\t-$(V_AT)mkdir -p $(JUCE_BINDIR)" << newLine
  273. << "\t-$(V_AT)mkdir -p $(JUCE_LIBDIR)" << newLine
  274. << "\t-$(V_AT)mkdir -p $(JUCE_OUTDIR)" << newLine;
  275. if (type == VST3PlugIn)
  276. out << "\t-$(V_AT)mkdir -p $(JUCE_OUTDIR)/$(JUCE_VST3DIR)/$(JUCE_VST3SUBDIR)" << newLine;
  277. else if (type == UnityPlugIn)
  278. out << "\t-$(V_AT)mkdir -p $(JUCE_OUTDIR)/$(JUCE_UNITYDIR)" << newLine;
  279. else if (type == LV2PlugIn)
  280. out << "\t-$(V_AT)mkdir -p $(JUCE_OUTDIR)/$(JUCE_LV2DIR)" << newLine;
  281. if (owner.projectType.isStaticLibrary() || type == SharedCodeTarget)
  282. {
  283. out << "\t$(V_AT)$(AR) -rcs " << getBuildProduct()
  284. << " $(OBJECTS_" << getTargetVarName() << ")" << newLine;
  285. }
  286. else
  287. {
  288. out << "\t$(V_AT)$(CXX) -o " << getBuildProduct()
  289. << " $(OBJECTS_" << getTargetVarName() << ") ";
  290. if (owner.shouldBuildTargetType (SharedCodeTarget))
  291. out << "$(JUCE_OUTDIR)/$(JUCE_TARGET_SHARED_CODE) ";
  292. out << "$(JUCE_LDFLAGS) ";
  293. if (getTargetFileType() == sharedLibraryOrDLL || getTargetFileType() == pluginBundle
  294. || type == GUIApp || type == StandalonePlugIn)
  295. out << "$(JUCE_LDFLAGS_" << getTargetVarName() << ") ";
  296. out << "$(RESOURCES) $(TARGET_ARCH)" << newLine;
  297. }
  298. if (type == VST3PlugIn)
  299. {
  300. out << "\t-$(V_AT)mkdir -p $(JUCE_VST3DESTDIR)" << newLine
  301. << "\t-$(V_AT)cp -R $(JUCE_COPYCMD_VST3)" << newLine;
  302. }
  303. else if (type == VSTPlugIn)
  304. {
  305. out << "\t-$(V_AT)mkdir -p $(JUCE_VSTDESTDIR)" << newLine
  306. << "\t-$(V_AT)cp -R $(JUCE_COPYCMD_VST)" << newLine;
  307. }
  308. else if (type == UnityPlugIn)
  309. {
  310. auto scriptName = owner.getProject().getUnityScriptName();
  311. build_tools::RelativePath scriptPath (owner.getProject().getGeneratedCodeFolder().getChildFile (scriptName),
  312. owner.getTargetFolder(),
  313. build_tools::RelativePath::projectFolder);
  314. out << "\t-$(V_AT)cp " + scriptPath.toUnixStyle() + " $(JUCE_OUTDIR)/$(JUCE_UNITYDIR)" << newLine
  315. << "\t-$(V_AT)mkdir -p $(JUCE_UNITYDESTDIR)" << newLine
  316. << "\t-$(V_AT)cp -R $(JUCE_COPYCMD_UNITY_PLUGIN)" << newLine;
  317. }
  318. else if (type == LV2PlugIn)
  319. {
  320. out << "\t$(V_AT) $(JUCE_OUTDIR)/$(JUCE_TARGET_LV2_MANIFEST_HELPER) "
  321. "$(abspath $(JUCE_LV2_FULL_PATH))" << newLine
  322. << "\t-$(V_AT)mkdir -p $(JUCE_LV2DESTDIR)" << newLine
  323. << "\t-$(V_AT)cp -R $(JUCE_COPYCMD_LV2_PLUGIN)" << newLine;
  324. }
  325. out << newLine;
  326. }
  327. const MakefileProjectExporter& owner;
  328. };
  329. //==============================================================================
  330. static String getDisplayName() { return "Linux Makefile"; }
  331. static String getValueTreeTypeName() { return "LINUX_MAKE"; }
  332. static String getTargetFolderName() { return "LinuxMakefile"; }
  333. Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }
  334. static MakefileProjectExporter* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
  335. {
  336. if (settingsToUse.hasType (getValueTreeTypeName()))
  337. return new MakefileProjectExporter (projectToUse, settingsToUse);
  338. return nullptr;
  339. }
  340. //==============================================================================
  341. MakefileProjectExporter (Project& p, const ValueTree& t)
  342. : ProjectExporter (p, t),
  343. extraPkgConfigValue (settings, Ids::linuxExtraPkgConfig, getUndoManager())
  344. {
  345. name = getDisplayName();
  346. targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderName());
  347. }
  348. //==============================================================================
  349. bool canLaunchProject() override { return false; }
  350. bool launchProject() override { return false; }
  351. bool usesMMFiles() const override { return false; }
  352. bool canCopeWithDuplicateFiles() override { return false; }
  353. bool supportsUserDefinedConfigurations() const override { return true; }
  354. bool isXcode() const override { return false; }
  355. bool isVisualStudio() const override { return false; }
  356. bool isCodeBlocks() const override { return false; }
  357. bool isMakefile() const override { return true; }
  358. bool isAndroidStudio() const override { return false; }
  359. bool isAndroid() const override { return false; }
  360. bool isWindows() const override { return false; }
  361. bool isLinux() const override { return true; }
  362. bool isOSX() const override { return false; }
  363. bool isiOS() const override { return false; }
  364. String getNewLineString() const override { return "\n"; }
  365. bool supportsTargetType (build_tools::ProjectType::Target::Type type) const override
  366. {
  367. using Target = build_tools::ProjectType::Target;
  368. switch (type)
  369. {
  370. case Target::GUIApp:
  371. case Target::ConsoleApp:
  372. case Target::StaticLibrary:
  373. case Target::SharedCodeTarget:
  374. case Target::AggregateTarget:
  375. case Target::VSTPlugIn:
  376. case Target::VST3PlugIn:
  377. case Target::StandalonePlugIn:
  378. case Target::DynamicLibrary:
  379. case Target::UnityPlugIn:
  380. case Target::LV2PlugIn:
  381. case Target::LV2TurtleProgram:
  382. return true;
  383. case Target::AAXPlugIn:
  384. case Target::AudioUnitPlugIn:
  385. case Target::AudioUnitv3PlugIn:
  386. case Target::unspecified:
  387. default:
  388. break;
  389. }
  390. return false;
  391. }
  392. void createExporterProperties (PropertyListBuilder& properties) override
  393. {
  394. properties.add (new TextPropertyComponent (extraPkgConfigValue, "pkg-config libraries", 8192, false),
  395. "Extra pkg-config libraries for you application. Each package should be space separated.");
  396. }
  397. void initialiseDependencyPathValues() override
  398. {
  399. vstLegacyPathValueWrapper.init ({ settings, Ids::vstLegacyFolder, nullptr },
  400. getAppSettings().getStoredPath (Ids::vstLegacyPath, TargetOS::linux), TargetOS::linux);
  401. }
  402. //==============================================================================
  403. bool anyTargetIsSharedLibrary() const
  404. {
  405. for (auto* target : targets)
  406. {
  407. auto fileType = target->getTargetFileType();
  408. if (fileType == build_tools::ProjectType::Target::sharedLibraryOrDLL
  409. || fileType == build_tools::ProjectType::Target::pluginBundle)
  410. return true;
  411. }
  412. return false;
  413. }
  414. //==============================================================================
  415. void create (const OwnedArray<LibraryModule>&) const override
  416. {
  417. build_tools::writeStreamToFile (getTargetFolder().getChildFile ("Makefile"), [&] (MemoryOutputStream& mo)
  418. {
  419. mo.setNewLineString (getNewLineString());
  420. writeMakefile (mo);
  421. });
  422. if (project.shouldBuildVST3())
  423. {
  424. auto helperDir = getTargetFolder().getChildFile ("make_helpers");
  425. helperDir.createDirectory();
  426. build_tools::overwriteFileIfDifferentOrThrow (helperDir.getChildFile ("arch_detection.cpp"),
  427. BinaryData::juce_runtime_arch_detection_cpp);
  428. }
  429. }
  430. //==============================================================================
  431. void addPlatformSpecificSettingsForProjectType (const build_tools::ProjectType&) override
  432. {
  433. callForAllSupportedTargets ([this] (build_tools::ProjectType::Target::Type targetType)
  434. {
  435. targets.insert (targetType == build_tools::ProjectType::Target::AggregateTarget ? 0 : -1,
  436. new MakefileTarget (targetType, *this));
  437. });
  438. // If you hit this assert, you tried to generate a project for an exporter
  439. // that does not support any of your targets!
  440. jassert (targets.size() > 0);
  441. }
  442. private:
  443. ValueTreePropertyWithDefault extraPkgConfigValue;
  444. //==============================================================================
  445. StringPairArray getDefines (const BuildConfiguration& config) const
  446. {
  447. StringPairArray result;
  448. result.set ("LINUX", "1");
  449. if (config.isDebug())
  450. {
  451. result.set ("DEBUG", "1");
  452. result.set ("_DEBUG", "1");
  453. }
  454. else
  455. {
  456. result.set ("NDEBUG", "1");
  457. }
  458. result = mergePreprocessorDefs (result, getAllPreprocessorDefs (config, build_tools::ProjectType::Target::unspecified));
  459. return result;
  460. }
  461. StringArray getExtraPkgConfigPackages() const
  462. {
  463. auto packages = StringArray::fromTokens (extraPkgConfigValue.get().toString(), " ", "\"'");
  464. packages.removeEmptyStrings();
  465. return packages;
  466. }
  467. StringArray getCompilePackages() const
  468. {
  469. auto packages = getLinuxPackages (PackageDependencyType::compile);
  470. packages.addArray (getExtraPkgConfigPackages());
  471. return packages;
  472. }
  473. StringArray getLinkPackages() const
  474. {
  475. auto packages = getLinuxPackages (PackageDependencyType::link);
  476. packages.addArray (getExtraPkgConfigPackages());
  477. return packages;
  478. }
  479. String getPreprocessorPkgConfigFlags() const
  480. {
  481. auto compilePackages = getCompilePackages();
  482. if (compilePackages.size() > 0)
  483. return "$(shell $(PKG_CONFIG) --cflags " + compilePackages.joinIntoString (" ") + ")";
  484. return {};
  485. }
  486. String getLinkerPkgConfigFlags() const
  487. {
  488. auto linkPackages = getLinkPackages();
  489. if (linkPackages.size() > 0)
  490. return "$(shell $(PKG_CONFIG) --libs " + linkPackages.joinIntoString (" ") + ")";
  491. return {};
  492. }
  493. StringArray getCPreprocessorFlags (const BuildConfiguration&) const
  494. {
  495. StringArray result;
  496. if (linuxLibs.contains ("pthread"))
  497. result.add ("-pthread");
  498. return result;
  499. }
  500. StringArray getCFlags (const BuildConfiguration& config) const
  501. {
  502. StringArray result;
  503. if (anyTargetIsSharedLibrary())
  504. result.add ("-fPIC");
  505. if (config.isDebug())
  506. {
  507. result.add ("-g");
  508. result.add ("-ggdb");
  509. }
  510. result.add ("-O" + config.getGCCOptimisationFlag());
  511. if (config.isLinkTimeOptimisationEnabled())
  512. result.add ("-flto");
  513. for (auto& recommended : config.getRecommendedCompilerWarningFlags().common)
  514. result.add (recommended);
  515. auto extra = replacePreprocessorTokens (config, getExtraCompilerFlagsString()).trim();
  516. if (extra.isNotEmpty())
  517. result.add (extra);
  518. return result;
  519. }
  520. StringArray getCXXFlags (const BuildConfiguration& config) const
  521. {
  522. StringArray result;
  523. for (auto& recommended : config.getRecommendedCompilerWarningFlags().cpp)
  524. result.add (recommended);
  525. auto cppStandard = project.getCppStandardString();
  526. if (cppStandard == "latest")
  527. cppStandard = project.getLatestNumberedCppStandardString();
  528. result.add ("-std=" + String (shouldUseGNUExtensions() ? "gnu++" : "c++") + cppStandard);
  529. return result;
  530. }
  531. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  532. {
  533. StringArray searchPaths (extraSearchPaths);
  534. searchPaths.addArray (config.getHeaderSearchPaths());
  535. searchPaths = getCleanedStringArray (searchPaths);
  536. StringArray result;
  537. for (auto& path : searchPaths)
  538. result.add (build_tools::unixStylePath (replacePreprocessorTokens (config, path)));
  539. return result;
  540. }
  541. StringArray getLibraryNames (const BuildConfiguration& config) const
  542. {
  543. StringArray result (linuxLibs);
  544. auto libraries = StringArray::fromTokens (getExternalLibrariesString(), ";", "\"'");
  545. libraries.removeEmptyStrings();
  546. for (auto& lib : libraries)
  547. result.add (replacePreprocessorTokens (config, lib).trim());
  548. return result;
  549. }
  550. StringArray getLibrarySearchPaths (const BuildConfiguration& config) const
  551. {
  552. auto result = getSearchPathsFromString (config.getLibrarySearchPathString());
  553. for (auto path : moduleLibSearchPaths)
  554. result.add (path + "/" + config.getModuleLibraryArchName());
  555. return result;
  556. }
  557. StringArray getLinkerFlags (const BuildConfiguration& config) const
  558. {
  559. auto result = makefileExtraLinkerFlags;
  560. result.add ("-fvisibility=hidden");
  561. if (config.isLinkTimeOptimisationEnabled())
  562. result.add ("-flto");
  563. auto extraFlags = getExtraLinkerFlagsString().trim();
  564. if (extraFlags.isNotEmpty())
  565. result.add (replacePreprocessorTokens (config, extraFlags));
  566. return result;
  567. }
  568. //==============================================================================
  569. void writeDefineFlags (OutputStream& out, const MakeBuildConfiguration& config) const
  570. {
  571. out << createGCCPreprocessorFlags (mergePreprocessorDefs (getDefines (config), getAllPreprocessorDefs (config, build_tools::ProjectType::Target::unspecified)));
  572. }
  573. void writePkgConfigFlags (OutputStream& out) const
  574. {
  575. auto flags = getPreprocessorPkgConfigFlags();
  576. if (flags.isNotEmpty())
  577. out << " " << flags;
  578. }
  579. void writeCPreprocessorFlags (OutputStream& out, const BuildConfiguration& config) const
  580. {
  581. auto flags = getCPreprocessorFlags (config);
  582. if (! flags.isEmpty())
  583. out << " " << flags.joinIntoString (" ");
  584. }
  585. void writeHeaderPathFlags (OutputStream& out, const BuildConfiguration& config) const
  586. {
  587. for (auto& path : getHeaderSearchPaths (config))
  588. out << " -I" << escapeQuotesAndSpaces (path).replace ("~", "$(HOME)");
  589. }
  590. void writeCppFlags (OutputStream& out, const MakeBuildConfiguration& config) const
  591. {
  592. out << " JUCE_CPPFLAGS := $(DEPFLAGS)";
  593. writeDefineFlags (out, config);
  594. writePkgConfigFlags (out);
  595. writeCPreprocessorFlags (out, config);
  596. writeHeaderPathFlags (out, config);
  597. out << " $(CPPFLAGS)" << newLine;
  598. }
  599. void writeLinkerFlags (OutputStream& out, const BuildConfiguration& config) const
  600. {
  601. out << " JUCE_LDFLAGS += $(TARGET_ARCH) -L$(JUCE_BINDIR) -L$(JUCE_LIBDIR)";
  602. for (auto path : getLibrarySearchPaths (config))
  603. out << " -L" << escapeQuotesAndSpaces (path).replace ("~", "$(HOME)");
  604. auto pkgConfigFlags = getLinkerPkgConfigFlags();
  605. if (pkgConfigFlags.isNotEmpty())
  606. out << " " << getLinkerPkgConfigFlags();
  607. auto linkerFlags = getLinkerFlags (config).joinIntoString (" ");
  608. if (linkerFlags.isNotEmpty())
  609. out << " " << linkerFlags;
  610. for (auto& libName : getLibraryNames (config))
  611. out << " -l" << libName;
  612. out << " $(LDFLAGS)" << newLine;
  613. }
  614. void writeTargetLines (OutputStream& out, const StringArray& packages) const
  615. {
  616. auto n = targets.size();
  617. for (int i = 0; i < n; ++i)
  618. {
  619. if (auto* target = targets.getUnchecked (i))
  620. {
  621. if (target->type == build_tools::ProjectType::Target::AggregateTarget)
  622. {
  623. StringArray dependencies;
  624. MemoryOutputStream subTargetLines;
  625. for (int j = 0; j < n; ++j)
  626. {
  627. if (i == j) continue;
  628. if (auto* dependency = targets.getUnchecked (j))
  629. {
  630. if (dependency->type != build_tools::ProjectType::Target::SharedCodeTarget)
  631. {
  632. auto phonyName = dependency->getPhonyName();
  633. subTargetLines << phonyName << " : " << dependency->getBuildProduct() << newLine;
  634. dependencies.add (phonyName);
  635. }
  636. }
  637. }
  638. out << "all : " << dependencies.joinIntoString (" ") << newLine << newLine;
  639. out << subTargetLines.toString() << newLine << newLine;
  640. }
  641. else
  642. {
  643. if (! getProject().isAudioPluginProject())
  644. out << "all : " << target->getBuildProduct() << newLine << newLine;
  645. target->writeTargetLine (out, packages);
  646. }
  647. }
  648. }
  649. }
  650. void writeConfig (OutputStream& out, const MakeBuildConfiguration& config) const
  651. {
  652. String buildDirName ("build");
  653. auto intermediatesDirName = buildDirName + "/intermediate/" + config.getName();
  654. auto outputDir = buildDirName;
  655. if (config.getTargetBinaryRelativePathString().isNotEmpty())
  656. {
  657. build_tools::RelativePath binaryPath (config.getTargetBinaryRelativePathString(), build_tools::RelativePath::projectFolder);
  658. outputDir = binaryPath.rebased (projectFolder, getTargetFolder(), build_tools::RelativePath::buildTargetFolder).toUnixStyle();
  659. }
  660. out << "ifeq ($(CONFIG)," << escapeQuotesAndSpaces (config.getName()) << ")" << newLine
  661. << " JUCE_BINDIR := " << escapeQuotesAndSpaces (buildDirName) << newLine
  662. << " JUCE_LIBDIR := " << escapeQuotesAndSpaces (buildDirName) << newLine
  663. << " JUCE_OBJDIR := " << escapeQuotesAndSpaces (intermediatesDirName) << newLine
  664. << " JUCE_OUTDIR := " << escapeQuotesAndSpaces (outputDir) << newLine
  665. << newLine
  666. << " ifeq ($(TARGET_ARCH),)" << newLine
  667. << " TARGET_ARCH := " << getArchFlags (config) << newLine
  668. << " endif" << newLine
  669. << newLine;
  670. writeCppFlags (out, config);
  671. for (auto target : targets)
  672. {
  673. auto lines = target->getTargetSettings (config);
  674. if (lines.size() > 0)
  675. out << " " << lines.joinIntoString ("\n ") << newLine;
  676. out << newLine;
  677. }
  678. out << " JUCE_CFLAGS += $(JUCE_CPPFLAGS) $(TARGET_ARCH)";
  679. auto cflags = getCFlags (config).joinIntoString (" ");
  680. if (cflags.isNotEmpty())
  681. out << " " << cflags;
  682. out << " $(CFLAGS)" << newLine;
  683. out << " JUCE_CXXFLAGS += $(JUCE_CFLAGS)";
  684. auto cxxflags = getCXXFlags (config).joinIntoString (" ");
  685. if (cxxflags.isNotEmpty())
  686. out << " " << cxxflags;
  687. out << " $(CXXFLAGS)" << newLine;
  688. writeLinkerFlags (out, config);
  689. out << newLine;
  690. out << " CLEANCMD = rm -rf $(JUCE_OUTDIR)/$(TARGET) $(JUCE_OBJDIR)" << newLine
  691. << "endif" << newLine
  692. << newLine;
  693. }
  694. void writeIncludeLines (OutputStream& out) const
  695. {
  696. auto n = targets.size();
  697. for (int i = 0; i < n; ++i)
  698. {
  699. if (auto* target = targets.getUnchecked (i))
  700. {
  701. if (target->type == build_tools::ProjectType::Target::AggregateTarget)
  702. continue;
  703. out << "-include $(OBJECTS_" << target->getTargetVarName()
  704. << ":%.o=%.d)" << newLine;
  705. }
  706. }
  707. }
  708. static String getCompilerFlagSchemeVariableName (const String& schemeName) { return "JUCE_COMPILERFLAGSCHEME_" + schemeName; }
  709. void findAllFilesToCompile (const Project::Item& projectItem, Array<std::pair<File, String>>& results) const
  710. {
  711. if (projectItem.isGroup())
  712. {
  713. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  714. findAllFilesToCompile (projectItem.getChild (i), results);
  715. }
  716. else
  717. {
  718. if (projectItem.shouldBeCompiled())
  719. {
  720. auto f = projectItem.getFile();
  721. if (shouldFileBeCompiledByDefault (f))
  722. {
  723. auto scheme = projectItem.getCompilerFlagSchemeString();
  724. auto flags = compilerFlagSchemesMap[scheme].get().toString();
  725. if (scheme.isNotEmpty() && flags.isNotEmpty())
  726. results.add ({ f, scheme });
  727. else
  728. results.add ({ f, {} });
  729. }
  730. }
  731. }
  732. }
  733. void writeCompilerFlagSchemes (OutputStream& out, const Array<std::pair<File, String>>& filesToCompile) const
  734. {
  735. StringArray schemesToWrite;
  736. for (auto& f : filesToCompile)
  737. if (f.second.isNotEmpty())
  738. schemesToWrite.addIfNotAlreadyThere (f.second);
  739. if (! schemesToWrite.isEmpty())
  740. {
  741. for (auto& s : schemesToWrite)
  742. out << getCompilerFlagSchemeVariableName (s) << " := "
  743. << compilerFlagSchemesMap[s].get().toString() << newLine;
  744. out << newLine;
  745. }
  746. }
  747. void writeMakefile (OutputStream& out) const
  748. {
  749. out << "# Automatically generated makefile, created by the Projucer" << newLine
  750. << "# Don't edit this file! Your changes will be overwritten when you re-save the Projucer project!" << newLine
  751. << newLine;
  752. out << "# build with \"V=1\" for verbose builds" << newLine
  753. << "ifeq ($(V), 1)" << newLine
  754. << "V_AT =" << newLine
  755. << "else" << newLine
  756. << "V_AT = @" << newLine
  757. << "endif" << newLine
  758. << newLine;
  759. out << "# (this disables dependency generation if multiple architectures are set)" << newLine
  760. << "DEPFLAGS := $(if $(word 2, $(TARGET_ARCH)), , -MMD)" << newLine
  761. << newLine;
  762. out << "ifndef PKG_CONFIG" << newLine
  763. << " PKG_CONFIG=pkg-config" << newLine
  764. << "endif" << newLine
  765. << newLine;
  766. out << "ifndef STRIP" << newLine
  767. << " STRIP=strip" << newLine
  768. << "endif" << newLine
  769. << newLine;
  770. out << "ifndef AR" << newLine
  771. << " AR=ar" << newLine
  772. << "endif" << newLine
  773. << newLine;
  774. out << "ifndef CONFIG" << newLine
  775. << " CONFIG=" << escapeQuotesAndSpaces (getConfiguration(0)->getName()) << newLine
  776. << "endif" << newLine
  777. << newLine;
  778. out << "JUCE_ARCH_LABEL := $(shell uname -m)" << newLine
  779. << newLine;
  780. for (ConstConfigIterator config (*this); config.next();)
  781. writeConfig (out, dynamic_cast<const MakeBuildConfiguration&> (*config));
  782. Array<std::pair<File, String>> filesToCompile;
  783. for (int i = 0; i < getAllGroups().size(); ++i)
  784. findAllFilesToCompile (getAllGroups().getReference (i), filesToCompile);
  785. writeCompilerFlagSchemes (out, filesToCompile);
  786. auto getFilesForTarget = [this] (const Array<std::pair<File, String>>& files,
  787. MakefileTarget* target,
  788. const Project& p) -> Array<std::pair<File, String>>
  789. {
  790. Array<std::pair<File, String>> targetFiles;
  791. auto targetType = (p.isAudioPluginProject() ? target->type : MakefileTarget::SharedCodeTarget);
  792. for (auto& f : files)
  793. if (p.getTargetTypeFromFilePath (f.first, true) == targetType)
  794. targetFiles.add (f);
  795. if (targetType == MakefileTarget::LV2TurtleProgram)
  796. targetFiles.add ({ project.resolveFilename (getLV2TurtleDumpProgramSource().toUnixStyle()), {} });
  797. return targetFiles;
  798. };
  799. for (auto target : targets)
  800. target->writeObjects (out, getFilesForTarget (filesToCompile, target, project));
  801. out << getPhonyTargetLine() << newLine << newLine;
  802. writeTargetLines (out, getLinkPackages());
  803. for (auto target : targets)
  804. target->addFiles (out, getFilesForTarget (filesToCompile, target, project));
  805. out << "clean:" << newLine
  806. << "\t@echo Cleaning " << projectName << newLine
  807. << "\t$(V_AT)$(CLEANCMD)" << newLine
  808. << newLine;
  809. out << "strip:" << newLine
  810. << "\t@echo Stripping " << projectName << newLine
  811. << "\t-$(V_AT)$(STRIP) --strip-unneeded $(JUCE_OUTDIR)/$(TARGET)" << newLine
  812. << newLine;
  813. writeIncludeLines (out);
  814. }
  815. String getArchFlags (const BuildConfiguration& config) const
  816. {
  817. if (auto* makeConfig = dynamic_cast<const MakeBuildConfiguration*> (&config))
  818. return makeConfig->getArchitectureTypeString();
  819. return "-march=native";
  820. }
  821. String getObjectFileFor (const build_tools::RelativePath& file) const
  822. {
  823. return file.getFileNameWithoutExtension()
  824. + "_" + String::toHexString (file.toUnixStyle().hashCode()) + ".o";
  825. }
  826. String getPhonyTargetLine() const
  827. {
  828. MemoryOutputStream phonyTargetLine;
  829. phonyTargetLine << ".PHONY: clean all strip";
  830. if (! getProject().isAudioPluginProject())
  831. return phonyTargetLine.toString();
  832. for (auto target : targets)
  833. if (target->type != build_tools::ProjectType::Target::SharedCodeTarget
  834. && target->type != build_tools::ProjectType::Target::AggregateTarget)
  835. phonyTargetLine << " " << target->getPhonyName();
  836. return phonyTargetLine.toString();
  837. }
  838. OwnedArray<MakefileTarget> targets;
  839. JUCE_DECLARE_NON_COPYABLE (MakefileProjectExporter)
  840. };