cmMakefileTargetGenerator.cxx 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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 "cmMakefileTargetGenerator.h"
  4. #include <memory>
  5. #include <sstream>
  6. #include <stdio.h>
  7. #include <utility>
  8. #include "cmAlgorithms.h"
  9. #include "cmComputeLinkInformation.h"
  10. #include "cmCustomCommand.h"
  11. #include "cmCustomCommandGenerator.h"
  12. #include "cmGeneratedFileStream.h"
  13. #include "cmGeneratorExpression.h"
  14. #include "cmGeneratorTarget.h"
  15. #include "cmGlobalUnixMakefileGenerator3.h"
  16. #include "cmLocalUnixMakefileGenerator3.h"
  17. #include "cmMakefile.h"
  18. #include "cmMakefileExecutableTargetGenerator.h"
  19. #include "cmMakefileLibraryTargetGenerator.h"
  20. #include "cmMakefileUtilityTargetGenerator.h"
  21. #include "cmOutputConverter.h"
  22. #include "cmRange.h"
  23. #include "cmRulePlaceholderExpander.h"
  24. #include "cmSourceFile.h"
  25. #include "cmState.h"
  26. #include "cmStateDirectory.h"
  27. #include "cmStateSnapshot.h"
  28. #include "cmStateTypes.h"
  29. #include "cmStringAlgorithms.h"
  30. #include "cmSystemTools.h"
  31. #include "cmake.h"
  32. cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
  33. : cmCommonTargetGenerator(target)
  34. , OSXBundleGenerator(nullptr)
  35. , MacOSXContentGenerator(nullptr)
  36. {
  37. this->BuildFileStream = nullptr;
  38. this->InfoFileStream = nullptr;
  39. this->FlagFileStream = nullptr;
  40. this->CustomCommandDriver = OnBuild;
  41. this->LocalGenerator =
  42. static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
  43. this->GlobalGenerator = static_cast<cmGlobalUnixMakefileGenerator3*>(
  44. this->LocalGenerator->GetGlobalGenerator());
  45. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  46. this->NoRuleMessages = false;
  47. if (const char* ruleStatus =
  48. cm->GetState()->GetGlobalProperty("RULE_MESSAGES")) {
  49. this->NoRuleMessages = cmIsOff(ruleStatus);
  50. }
  51. MacOSXContentGenerator = new MacOSXContentGeneratorType(this);
  52. }
  53. cmMakefileTargetGenerator::~cmMakefileTargetGenerator()
  54. {
  55. delete MacOSXContentGenerator;
  56. }
  57. cmMakefileTargetGenerator* cmMakefileTargetGenerator::New(
  58. cmGeneratorTarget* tgt)
  59. {
  60. cmMakefileTargetGenerator* result = nullptr;
  61. switch (tgt->GetType()) {
  62. case cmStateEnums::EXECUTABLE:
  63. result = new cmMakefileExecutableTargetGenerator(tgt);
  64. break;
  65. case cmStateEnums::STATIC_LIBRARY:
  66. case cmStateEnums::SHARED_LIBRARY:
  67. case cmStateEnums::MODULE_LIBRARY:
  68. case cmStateEnums::OBJECT_LIBRARY:
  69. result = new cmMakefileLibraryTargetGenerator(tgt);
  70. break;
  71. case cmStateEnums::UTILITY:
  72. result = new cmMakefileUtilityTargetGenerator(tgt);
  73. break;
  74. default:
  75. return result;
  76. // break; /* unreachable */
  77. }
  78. return result;
  79. }
  80. void cmMakefileTargetGenerator::GetTargetLinkFlags(
  81. std::string& flags, const std::string& linkLanguage)
  82. {
  83. this->LocalGenerator->AppendFlags(
  84. flags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
  85. std::string linkFlagsConfig =
  86. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(this->ConfigName));
  87. this->LocalGenerator->AppendFlags(
  88. flags, this->GeneratorTarget->GetProperty(linkFlagsConfig));
  89. std::vector<std::string> opts;
  90. this->GeneratorTarget->GetLinkOptions(opts, this->ConfigName, linkLanguage);
  91. // LINK_OPTIONS are escaped.
  92. this->LocalGenerator->AppendCompileOptions(flags, opts);
  93. this->LocalGenerator->AppendPositionIndependentLinkerFlags(
  94. flags, this->GeneratorTarget, this->ConfigName, linkLanguage);
  95. }
  96. void cmMakefileTargetGenerator::CreateRuleFile()
  97. {
  98. // Create a directory for this target.
  99. this->TargetBuildDirectory =
  100. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  101. this->TargetBuildDirectoryFull =
  102. this->LocalGenerator->ConvertToFullPath(this->TargetBuildDirectory);
  103. cmSystemTools::MakeDirectory(this->TargetBuildDirectoryFull);
  104. // Construct the rule file name.
  105. this->BuildFileName = cmStrCat(this->TargetBuildDirectory, "/build.make");
  106. this->BuildFileNameFull =
  107. cmStrCat(this->TargetBuildDirectoryFull, "/build.make");
  108. // Construct the rule file name.
  109. this->ProgressFileNameFull =
  110. cmStrCat(this->TargetBuildDirectoryFull, "/progress.make");
  111. // reset the progress count
  112. this->NumberOfProgressActions = 0;
  113. // Open the rule file. This should be copy-if-different because the
  114. // rules may depend on this file itself.
  115. this->BuildFileStream =
  116. new cmGeneratedFileStream(this->BuildFileNameFull, false,
  117. this->GlobalGenerator->GetMakefileEncoding());
  118. if (!this->BuildFileStream) {
  119. return;
  120. }
  121. this->BuildFileStream->SetCopyIfDifferent(true);
  122. this->LocalGenerator->WriteDisclaimer(*this->BuildFileStream);
  123. if (this->GlobalGenerator->AllowDeleteOnError()) {
  124. std::vector<std::string> no_depends;
  125. std::vector<std::string> no_commands;
  126. this->LocalGenerator->WriteMakeRule(
  127. *this->BuildFileStream, "Delete rule output on recipe failure.",
  128. ".DELETE_ON_ERROR", no_depends, no_commands, false);
  129. }
  130. this->LocalGenerator->WriteSpecialTargetsTop(*this->BuildFileStream);
  131. }
  132. void cmMakefileTargetGenerator::WriteTargetBuildRules()
  133. {
  134. // -- Write the custom commands for this target
  135. const std::string& config =
  136. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  137. // Evaluates generator expressions and expands prop_value
  138. auto evaluatedFiles =
  139. [this, &config](const char* prop_value) -> std::vector<std::string> {
  140. std::vector<std::string> files;
  141. cmGeneratorExpression ge;
  142. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop_value);
  143. cmExpandList(cge->Evaluate(this->LocalGenerator, config, false,
  144. this->GeneratorTarget, nullptr, nullptr),
  145. files);
  146. return files;
  147. };
  148. // Look for additional files registered for cleaning in this directory.
  149. if (const char* prop_value =
  150. this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
  151. std::vector<std::string> const files = evaluatedFiles(prop_value);
  152. this->CleanFiles.insert(files.begin(), files.end());
  153. }
  154. // Look for additional files registered for cleaning in this target.
  155. if (const char* prop_value =
  156. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  157. std::vector<std::string> const files = evaluatedFiles(prop_value);
  158. // For relative path support
  159. std::string const& binaryDir =
  160. this->LocalGenerator->GetCurrentBinaryDirectory();
  161. for (std::string const& cfl : files) {
  162. this->CleanFiles.insert(cmSystemTools::CollapseFullPath(cfl, binaryDir));
  163. }
  164. }
  165. // add custom commands to the clean rules?
  166. const char* clean_no_custom = this->Makefile->GetProperty("CLEAN_NO_CUSTOM");
  167. bool clean = cmIsOff(clean_no_custom);
  168. // First generate the object rule files. Save a list of all object
  169. // files for this target.
  170. std::vector<cmSourceFile const*> customCommands;
  171. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  172. std::string currentBinDir =
  173. this->LocalGenerator->GetCurrentBinaryDirectory();
  174. for (cmSourceFile const* sf : customCommands) {
  175. cmCustomCommandGenerator ccg(*sf->GetCustomCommand(), this->ConfigName,
  176. this->LocalGenerator);
  177. this->GenerateCustomRuleFile(ccg);
  178. if (clean) {
  179. const std::vector<std::string>& outputs = ccg.GetOutputs();
  180. for (std::string const& output : outputs) {
  181. this->CleanFiles.insert(
  182. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  183. output));
  184. }
  185. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  186. for (std::string const& byproduct : byproducts) {
  187. this->CleanFiles.insert(
  188. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  189. byproduct));
  190. }
  191. }
  192. }
  193. // Add byproducts from build events to the clean rules
  194. if (clean) {
  195. std::vector<cmCustomCommand> buildEventCommands =
  196. this->GeneratorTarget->GetPreBuildCommands();
  197. cmAppend(buildEventCommands, this->GeneratorTarget->GetPreLinkCommands());
  198. cmAppend(buildEventCommands,
  199. this->GeneratorTarget->GetPostBuildCommands());
  200. for (const auto& be : buildEventCommands) {
  201. const std::vector<std::string>& byproducts = be.GetByproducts();
  202. for (std::string const& byproduct : byproducts) {
  203. this->CleanFiles.insert(
  204. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  205. byproduct));
  206. }
  207. }
  208. }
  209. std::vector<cmSourceFile const*> headerSources;
  210. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  211. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  212. headerSources, this->MacOSXContentGenerator);
  213. std::vector<cmSourceFile const*> extraSources;
  214. this->GeneratorTarget->GetExtraSources(extraSources, config);
  215. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  216. extraSources, this->MacOSXContentGenerator);
  217. const char* pchExtension =
  218. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  219. std::vector<cmSourceFile const*> externalObjects;
  220. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  221. for (cmSourceFile const* sf : externalObjects) {
  222. auto const& objectFileName = sf->GetFullPath();
  223. if (!cmSystemTools::StringEndsWith(objectFileName, pchExtension)) {
  224. this->ExternalObjects.push_back(objectFileName);
  225. }
  226. }
  227. std::vector<cmSourceFile const*> objectSources;
  228. this->GeneratorTarget->GetObjectSources(objectSources, config);
  229. for (cmSourceFile const* sf : objectSources) {
  230. // Generate this object file's rule file.
  231. this->WriteObjectRuleFiles(*sf);
  232. }
  233. }
  234. void cmMakefileTargetGenerator::WriteCommonCodeRules()
  235. {
  236. const char* root = (this->Makefile->IsOn("CMAKE_MAKE_INCLUDE_FROM_ROOT")
  237. ? "$(CMAKE_BINARY_DIR)/"
  238. : "");
  239. // Include the dependencies for the target.
  240. std::string dependFileNameFull =
  241. cmStrCat(this->TargetBuildDirectoryFull, "/depend.make");
  242. *this->BuildFileStream
  243. << "# Include any dependencies generated for this target.\n"
  244. << this->GlobalGenerator->IncludeDirective << " " << root
  245. << cmSystemTools::ConvertToOutputPath(
  246. this->LocalGenerator->MaybeConvertToRelativePath(
  247. this->LocalGenerator->GetBinaryDirectory(), dependFileNameFull))
  248. << "\n\n";
  249. if (!this->NoRuleMessages) {
  250. // Include the progress variables for the target.
  251. *this->BuildFileStream
  252. << "# Include the progress variables for this target.\n"
  253. << this->GlobalGenerator->IncludeDirective << " " << root
  254. << cmSystemTools::ConvertToOutputPath(
  255. this->LocalGenerator->MaybeConvertToRelativePath(
  256. this->LocalGenerator->GetBinaryDirectory(),
  257. this->ProgressFileNameFull))
  258. << "\n\n";
  259. }
  260. // make sure the depend file exists
  261. if (!cmSystemTools::FileExists(dependFileNameFull)) {
  262. // Write an empty dependency file.
  263. cmGeneratedFileStream depFileStream(
  264. dependFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  265. depFileStream << "# Empty dependencies file for "
  266. << this->GeneratorTarget->GetName() << ".\n"
  267. << "# This may be replaced when dependencies are built."
  268. << std::endl;
  269. }
  270. // Open the flags file. This should be copy-if-different because the
  271. // rules may depend on this file itself.
  272. this->FlagFileNameFull =
  273. cmStrCat(this->TargetBuildDirectoryFull, "/flags.make");
  274. this->FlagFileStream =
  275. new cmGeneratedFileStream(this->FlagFileNameFull, false,
  276. this->GlobalGenerator->GetMakefileEncoding());
  277. if (!this->FlagFileStream) {
  278. return;
  279. }
  280. this->FlagFileStream->SetCopyIfDifferent(true);
  281. this->LocalGenerator->WriteDisclaimer(*this->FlagFileStream);
  282. // Include the flags for the target.
  283. *this->BuildFileStream
  284. << "# Include the compile flags for this target's objects.\n"
  285. << this->GlobalGenerator->IncludeDirective << " " << root
  286. << cmSystemTools::ConvertToOutputPath(
  287. this->LocalGenerator->MaybeConvertToRelativePath(
  288. this->LocalGenerator->GetBinaryDirectory(), this->FlagFileNameFull))
  289. << "\n\n";
  290. }
  291. void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  292. {
  293. // write language flags for target
  294. std::set<std::string> languages;
  295. this->GeneratorTarget->GetLanguages(
  296. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  297. // put the compiler in the rules.make file so that if it changes
  298. // things rebuild
  299. for (std::string const& language : languages) {
  300. std::string compiler = cmStrCat("CMAKE_", language, "_COMPILER");
  301. *this->FlagFileStream << "# compile " << language << " with "
  302. << this->Makefile->GetSafeDefinition(compiler)
  303. << "\n";
  304. }
  305. for (std::string const& language : languages) {
  306. std::string flags = this->GetFlags(language);
  307. std::string defines = this->GetDefines(language);
  308. std::string includes = this->GetIncludes(language);
  309. // Escape comment characters so they do not terminate assignment.
  310. cmSystemTools::ReplaceString(flags, "#", "\\#");
  311. cmSystemTools::ReplaceString(defines, "#", "\\#");
  312. cmSystemTools::ReplaceString(includes, "#", "\\#");
  313. *this->FlagFileStream << language << "_FLAGS = " << flags << "\n\n";
  314. *this->FlagFileStream << language << "_DEFINES = " << defines << "\n\n";
  315. *this->FlagFileStream << language << "_INCLUDES = " << includes << "\n\n";
  316. }
  317. }
  318. void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
  319. cmSourceFile const& source, const char* pkgloc)
  320. {
  321. // Skip OS X content when not building a Framework or Bundle.
  322. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  323. return;
  324. }
  325. std::string macdir =
  326. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc);
  327. // Get the input file location.
  328. std::string const& input = source.GetFullPath();
  329. // Get the output file location.
  330. std::string output =
  331. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  332. this->Generator->CleanFiles.insert(
  333. this->Generator->LocalGenerator->MaybeConvertToRelativePath(
  334. this->Generator->LocalGenerator->GetCurrentBinaryDirectory(), output));
  335. output = this->Generator->LocalGenerator->MaybeConvertToRelativePath(
  336. this->Generator->LocalGenerator->GetBinaryDirectory(), output);
  337. // Create a rule to copy the content into the bundle.
  338. std::vector<std::string> depends;
  339. std::vector<std::string> commands;
  340. depends.push_back(input);
  341. std::string copyEcho = cmStrCat("Copying OS X content ", output);
  342. this->Generator->LocalGenerator->AppendEcho(
  343. commands, copyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  344. std::string copyCommand =
  345. cmStrCat("$(CMAKE_COMMAND) -E copy ",
  346. this->Generator->LocalGenerator->ConvertToOutputFormat(
  347. input, cmOutputConverter::SHELL),
  348. ' ',
  349. this->Generator->LocalGenerator->ConvertToOutputFormat(
  350. output, cmOutputConverter::SHELL));
  351. commands.push_back(std::move(copyCommand));
  352. this->Generator->LocalGenerator->WriteMakeRule(
  353. *this->Generator->BuildFileStream, nullptr, output, depends, commands,
  354. false);
  355. this->Generator->ExtraFiles.insert(output);
  356. }
  357. void cmMakefileTargetGenerator::WriteObjectRuleFiles(
  358. cmSourceFile const& source)
  359. {
  360. // Identify the language of the source file.
  361. const std::string& lang =
  362. this->LocalGenerator->GetSourceFileLanguage(source);
  363. if (lang.empty()) {
  364. // don't know anything about this file so skip it
  365. return;
  366. }
  367. // Get the full path name of the object file.
  368. std::string const& objectName =
  369. this->GeneratorTarget->GetObjectName(&source);
  370. std::string obj =
  371. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  372. '/', objectName);
  373. // Avoid generating duplicate rules.
  374. if (this->ObjectFiles.find(obj) == this->ObjectFiles.end()) {
  375. this->ObjectFiles.insert(obj);
  376. } else {
  377. std::ostringstream err;
  378. err << "Warning: Source file \"" << source.GetFullPath()
  379. << "\" is listed multiple times for target \""
  380. << this->GeneratorTarget->GetName() << "\".";
  381. cmSystemTools::Message(err.str(), "Warning");
  382. return;
  383. }
  384. // Create the directory containing the object file. This may be a
  385. // subdirectory under the target's directory.
  386. std::string dir = cmSystemTools::GetFilenamePath(obj);
  387. cmSystemTools::MakeDirectory(this->LocalGenerator->ConvertToFullPath(dir));
  388. // Save this in the target's list of object files.
  389. this->Objects.push_back(obj);
  390. this->CleanFiles.insert(obj);
  391. // TODO: Remove
  392. // std::string relativeObj
  393. //= this->LocalGenerator->GetHomeRelativeOutputPath();
  394. // relativeObj += obj;
  395. // we compute some depends when writing the depend.make that we will also
  396. // use in the build.make, same with depMakeFile
  397. std::vector<std::string> depends;
  398. // generate the build rule file
  399. this->WriteObjectBuildFile(obj, lang, source, depends);
  400. // The object file should be checked for dependency integrity.
  401. std::string objFullPath =
  402. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', obj);
  403. objFullPath = cmSystemTools::CollapseFullPath(objFullPath);
  404. std::string srcFullPath =
  405. cmSystemTools::CollapseFullPath(source.GetFullPath());
  406. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, lang,
  407. objFullPath, srcFullPath);
  408. }
  409. void cmMakefileTargetGenerator::WriteObjectBuildFile(
  410. std::string& obj, const std::string& lang, cmSourceFile const& source,
  411. std::vector<std::string>& depends)
  412. {
  413. this->LocalGenerator->AppendRuleDepend(depends,
  414. this->FlagFileNameFull.c_str());
  415. this->LocalGenerator->AppendRuleDepends(depends,
  416. this->FlagFileDepends[lang]);
  417. // generate the depend scanning rule
  418. this->WriteObjectDependRules(source, depends);
  419. std::string relativeObj =
  420. cmStrCat(this->LocalGenerator->GetHomeRelativeOutputPath(), obj);
  421. // Write the build rule.
  422. // Build the set of compiler flags.
  423. std::string flags;
  424. // Add language-specific flags.
  425. std::string langFlags = cmStrCat("$(", lang, "_FLAGS)");
  426. this->LocalGenerator->AppendFlags(flags, langFlags);
  427. std::string config = this->LocalGenerator->GetConfigName();
  428. std::string configUpper = cmSystemTools::UpperCase(config);
  429. cmGeneratorExpressionInterpreter genexInterpreter(
  430. this->LocalGenerator, config, this->GeneratorTarget, lang);
  431. // Add Fortran format flags.
  432. if (lang == "Fortran") {
  433. this->AppendFortranFormatFlags(flags, source);
  434. }
  435. // Add flags from source file properties.
  436. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  437. if (const char* cflags = source.GetProperty(COMPILE_FLAGS)) {
  438. const std::string& evaluatedFlags =
  439. genexInterpreter.Evaluate(cflags, COMPILE_FLAGS);
  440. this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
  441. *this->FlagFileStream << "# Custom flags: " << relativeObj
  442. << "_FLAGS = " << evaluatedFlags << "\n"
  443. << "\n";
  444. }
  445. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  446. if (const char* coptions = source.GetProperty(COMPILE_OPTIONS)) {
  447. const std::string& evaluatedOptions =
  448. genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS);
  449. this->LocalGenerator->AppendCompileOptions(flags, evaluatedOptions);
  450. *this->FlagFileStream << "# Custom options: " << relativeObj
  451. << "_OPTIONS = " << evaluatedOptions << "\n"
  452. << "\n";
  453. }
  454. // Add include directories from source file properties.
  455. std::vector<std::string> includes;
  456. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  457. if (const char* cincludes = source.GetProperty(INCLUDE_DIRECTORIES)) {
  458. const std::string& evaluatedIncludes =
  459. genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES);
  460. this->LocalGenerator->AppendIncludeDirectories(includes, evaluatedIncludes,
  461. source);
  462. *this->FlagFileStream << "# Custom include directories: " << relativeObj
  463. << "_INCLUDE_DIRECTORIES = " << evaluatedIncludes
  464. << "\n"
  465. << "\n";
  466. }
  467. // Add language-specific defines.
  468. std::set<std::string> defines;
  469. // Add source-specific preprocessor definitions.
  470. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  471. if (const char* compile_defs = source.GetProperty(COMPILE_DEFINITIONS)) {
  472. const std::string& evaluatedDefs =
  473. genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS);
  474. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  475. *this->FlagFileStream << "# Custom defines: " << relativeObj
  476. << "_DEFINES = " << evaluatedDefs << "\n"
  477. << "\n";
  478. }
  479. std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
  480. if (const char* config_compile_defs = source.GetProperty(defPropName)) {
  481. const std::string& evaluatedDefs =
  482. genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS);
  483. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  484. *this->FlagFileStream << "# Custom defines: " << relativeObj << "_DEFINES_"
  485. << configUpper << " = " << evaluatedDefs << "\n"
  486. << "\n";
  487. }
  488. // Get the output paths for source and object files.
  489. std::string sourceFile = this->LocalGenerator->ConvertToOutputFormat(
  490. source.GetFullPath(), cmOutputConverter::SHELL);
  491. // Construct the build message.
  492. std::vector<std::string> no_commands;
  493. std::vector<std::string> commands;
  494. // add in a progress call if needed
  495. this->NumberOfProgressActions++;
  496. if (!this->NoRuleMessages) {
  497. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  498. this->MakeEchoProgress(progress);
  499. std::string buildEcho =
  500. cmStrCat("Building ", lang, " object ", relativeObj);
  501. this->LocalGenerator->AppendEcho(commands, buildEcho,
  502. cmLocalUnixMakefileGenerator3::EchoBuild,
  503. &progress);
  504. }
  505. std::string targetOutPathReal;
  506. std::string targetOutPathPDB;
  507. std::string targetOutPathCompilePDB;
  508. {
  509. std::string targetFullPathReal;
  510. std::string targetFullPathPDB;
  511. std::string targetFullPathCompilePDB = this->ComputeTargetCompilePDB();
  512. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  513. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  514. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  515. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  516. targetFullPathReal = this->GeneratorTarget->GetFullPath(
  517. this->ConfigName, cmStateEnums::RuntimeBinaryArtifact, true);
  518. targetFullPathPDB =
  519. cmStrCat(this->GeneratorTarget->GetPDBDirectory(this->ConfigName), '/',
  520. this->GeneratorTarget->GetPDBName(this->ConfigName));
  521. }
  522. targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
  523. this->LocalGenerator->MaybeConvertToRelativePath(
  524. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
  525. cmOutputConverter::SHELL);
  526. targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
  527. targetFullPathPDB, cmOutputConverter::SHELL);
  528. targetOutPathCompilePDB = this->LocalGenerator->ConvertToOutputFormat(
  529. this->LocalGenerator->MaybeConvertToRelativePath(
  530. this->LocalGenerator->GetCurrentBinaryDirectory(),
  531. targetFullPathCompilePDB),
  532. cmOutputConverter::SHELL);
  533. if (this->LocalGenerator->IsMinGWMake() &&
  534. cmHasLiteralSuffix(targetOutPathCompilePDB, "\\")) {
  535. // mingw32-make incorrectly interprets 'a\ b c' as 'a b' and 'c'
  536. // (but 'a\ b "c"' as 'a\', 'b', and 'c'!). Workaround this by
  537. // avoiding a trailing backslash in the argument.
  538. targetOutPathCompilePDB.back() = '/';
  539. }
  540. }
  541. cmRulePlaceholderExpander::RuleVariables vars;
  542. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  543. vars.CMTargetType =
  544. cmState::GetTargetTypeName(this->GeneratorTarget->GetType());
  545. vars.Language = lang.c_str();
  546. vars.Target = targetOutPathReal.c_str();
  547. vars.TargetPDB = targetOutPathPDB.c_str();
  548. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  549. vars.Source = sourceFile.c_str();
  550. std::string shellObj =
  551. this->LocalGenerator->ConvertToOutputFormat(obj, cmOutputConverter::SHELL);
  552. vars.Object = shellObj.c_str();
  553. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  554. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  555. this->LocalGenerator->MaybeConvertToRelativePath(
  556. this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
  557. cmOutputConverter::SHELL);
  558. vars.ObjectDir = objectDir.c_str();
  559. std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
  560. objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
  561. this->LocalGenerator->MaybeConvertToRelativePath(
  562. this->LocalGenerator->GetCurrentBinaryDirectory(), objectFileDir),
  563. cmOutputConverter::SHELL);
  564. vars.ObjectFileDir = objectFileDir.c_str();
  565. vars.Flags = flags.c_str();
  566. std::string definesString = cmStrCat("$(", lang, "_DEFINES)");
  567. this->LocalGenerator->JoinDefines(defines, definesString, lang);
  568. vars.Defines = definesString.c_str();
  569. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  570. includes, this->GeneratorTarget, lang, true, false, config);
  571. this->LocalGenerator->AppendFlags(includesString,
  572. "$(" + lang + "_INCLUDES)");
  573. vars.Includes = includesString.c_str();
  574. // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
  575. // assembly and preprocessor capabilities. The same is true for the
  576. // ability to export compile commands
  577. bool lang_has_preprocessor = ((lang == "C") || (lang == "CXX") ||
  578. (lang == "Fortran") || (lang == "CUDA"));
  579. bool const lang_has_assembly = lang_has_preprocessor;
  580. bool const lang_can_export_cmds = lang_has_preprocessor;
  581. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  582. this->LocalGenerator->CreateRulePlaceholderExpander());
  583. // Construct the compile rules.
  584. {
  585. std::vector<std::string> compileCommands;
  586. if (lang == "CUDA") {
  587. std::string cmdVar;
  588. if (this->GeneratorTarget->GetPropertyAsBool(
  589. "CUDA_SEPARABLE_COMPILATION")) {
  590. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  591. } else if (this->GeneratorTarget->GetPropertyAsBool(
  592. "CUDA_PTX_COMPILATION")) {
  593. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  594. } else {
  595. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  596. }
  597. const std::string& compileRule =
  598. this->Makefile->GetRequiredDefinition(cmdVar);
  599. cmExpandList(compileRule, compileCommands);
  600. } else {
  601. const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT";
  602. const std::string& compileRule =
  603. this->Makefile->GetRequiredDefinition(cmdVar);
  604. cmExpandList(compileRule, compileCommands);
  605. }
  606. if (this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS") &&
  607. lang_can_export_cmds && compileCommands.size() == 1) {
  608. std::string compileCommand = compileCommands[0];
  609. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  610. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  611. compileCommand, vars);
  612. std::string workingDirectory = cmSystemTools::CollapseFullPath(
  613. this->LocalGenerator->GetCurrentBinaryDirectory());
  614. compileCommand.replace(compileCommand.find(langFlags), langFlags.size(),
  615. this->GetFlags(lang));
  616. std::string langDefines = std::string("$(") + lang + "_DEFINES)";
  617. compileCommand.replace(compileCommand.find(langDefines),
  618. langDefines.size(), this->GetDefines(lang));
  619. std::string langIncludes = std::string("$(") + lang + "_INCLUDES)";
  620. compileCommand.replace(compileCommand.find(langIncludes),
  621. langIncludes.size(), this->GetIncludes(lang));
  622. const char* eliminate[] = {
  623. this->Makefile->GetDefinition("CMAKE_START_TEMP_FILE"),
  624. this->Makefile->GetDefinition("CMAKE_END_TEMP_FILE")
  625. };
  626. for (const char* el : eliminate) {
  627. if (el) {
  628. cmSystemTools::ReplaceString(compileCommand, el, "");
  629. }
  630. }
  631. this->GlobalGenerator->AddCXXCompileCommand(
  632. source.GetFullPath(), workingDirectory, compileCommand);
  633. }
  634. // See if we need to use a compiler launcher like ccache or distcc
  635. std::string compilerLauncher;
  636. if (!compileCommands.empty() &&
  637. (lang == "C" || lang == "CXX" || lang == "Fortran" ||
  638. lang == "CUDA")) {
  639. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  640. const char* clauncher =
  641. this->GeneratorTarget->GetProperty(clauncher_prop);
  642. if (clauncher && *clauncher) {
  643. compilerLauncher = clauncher;
  644. }
  645. }
  646. // Maybe insert an include-what-you-use runner.
  647. if (!compileCommands.empty() && (lang == "C" || lang == "CXX")) {
  648. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  649. const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  650. std::string const tidy_prop = lang + "_CLANG_TIDY";
  651. const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  652. std::string const cpplint_prop = lang + "_CPPLINT";
  653. const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  654. std::string const cppcheck_prop = lang + "_CPPCHECK";
  655. const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  656. if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
  657. (cppcheck && *cppcheck)) {
  658. std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile";
  659. if (!compilerLauncher.empty()) {
  660. // In __run_co_compile case the launcher command is supplied
  661. // via --launcher=<maybe-list> and consumed
  662. run_iwyu += " --launcher=";
  663. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  664. compilerLauncher.clear();
  665. }
  666. if (iwyu && *iwyu) {
  667. run_iwyu += " --iwyu=";
  668. run_iwyu += this->LocalGenerator->EscapeForShell(iwyu);
  669. }
  670. if (tidy && *tidy) {
  671. run_iwyu += " --tidy=";
  672. run_iwyu += this->LocalGenerator->EscapeForShell(tidy);
  673. }
  674. if (cpplint && *cpplint) {
  675. run_iwyu += " --cpplint=";
  676. run_iwyu += this->LocalGenerator->EscapeForShell(cpplint);
  677. }
  678. if (cppcheck && *cppcheck) {
  679. run_iwyu += " --cppcheck=";
  680. run_iwyu += this->LocalGenerator->EscapeForShell(cppcheck);
  681. }
  682. if ((tidy && *tidy) || (cpplint && *cpplint) ||
  683. (cppcheck && *cppcheck)) {
  684. run_iwyu += " --source=";
  685. run_iwyu += sourceFile;
  686. }
  687. run_iwyu += " -- ";
  688. compileCommands.front().insert(0, run_iwyu);
  689. }
  690. }
  691. // If compiler launcher was specified and not consumed above, it
  692. // goes to the beginning of the command line.
  693. if (!compileCommands.empty() && !compilerLauncher.empty()) {
  694. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  695. if (!args.empty()) {
  696. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  697. args[0], cmOutputConverter::SHELL);
  698. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  699. i = this->LocalGenerator->EscapeForShell(i);
  700. }
  701. }
  702. compileCommands.front().insert(0, cmJoin(args, " ") + " ");
  703. }
  704. std::string launcher;
  705. {
  706. const char* val = this->LocalGenerator->GetRuleLauncher(
  707. this->GeneratorTarget, "RULE_LAUNCH_COMPILE");
  708. if (val && *val) {
  709. launcher = cmStrCat(val, ' ');
  710. }
  711. }
  712. // Expand placeholders in the commands.
  713. for (std::string& compileCommand : compileCommands) {
  714. compileCommand = cmStrCat(launcher, compileCommand);
  715. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  716. compileCommand, vars);
  717. }
  718. // Change the command working directory to the local build tree.
  719. this->LocalGenerator->CreateCDCommand(
  720. compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  721. this->LocalGenerator->GetBinaryDirectory());
  722. cmAppend(commands, compileCommands);
  723. }
  724. // Check for extra outputs created by the compilation.
  725. std::vector<std::string> outputs(1, relativeObj);
  726. if (const char* extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) {
  727. // Register these as extra files to clean.
  728. cmExpandList(extra_outputs_str, outputs);
  729. this->CleanFiles.insert(outputs.begin() + 1, outputs.end());
  730. }
  731. // Write the rule.
  732. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  733. commands);
  734. bool do_preprocess_rules = lang_has_preprocessor &&
  735. this->LocalGenerator->GetCreatePreprocessedSourceRules();
  736. bool do_assembly_rules =
  737. lang_has_assembly && this->LocalGenerator->GetCreateAssemblySourceRules();
  738. if (do_preprocess_rules || do_assembly_rules) {
  739. std::vector<std::string> force_depends;
  740. force_depends.emplace_back("cmake_force");
  741. std::string::size_type dot_pos = relativeObj.rfind('.');
  742. std::string relativeObjBase = relativeObj.substr(0, dot_pos);
  743. dot_pos = obj.rfind('.');
  744. std::string objBase = obj.substr(0, dot_pos);
  745. if (do_preprocess_rules) {
  746. commands.clear();
  747. std::string relativeObjI = relativeObjBase + ".i";
  748. std::string objI = objBase + ".i";
  749. std::string preprocessEcho =
  750. cmStrCat("Preprocessing ", lang, " source to ", objI);
  751. this->LocalGenerator->AppendEcho(
  752. commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  753. std::string preprocessRuleVar =
  754. cmStrCat("CMAKE_", lang, "_CREATE_PREPROCESSED_SOURCE");
  755. if (const char* preprocessRule =
  756. this->Makefile->GetDefinition(preprocessRuleVar)) {
  757. std::vector<std::string> preprocessCommands =
  758. cmExpandedList(preprocessRule);
  759. std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
  760. objI, cmOutputConverter::SHELL);
  761. vars.PreprocessedSource = shellObjI.c_str();
  762. // Expand placeholders in the commands.
  763. for (std::string& preprocessCommand : preprocessCommands) {
  764. // no launcher for preprocessor commands
  765. rulePlaceholderExpander->ExpandRuleVariables(
  766. this->LocalGenerator, preprocessCommand, vars);
  767. }
  768. this->LocalGenerator->CreateCDCommand(
  769. preprocessCommands,
  770. this->LocalGenerator->GetCurrentBinaryDirectory(),
  771. this->LocalGenerator->GetBinaryDirectory());
  772. cmAppend(commands, preprocessCommands);
  773. } else {
  774. std::string cmd =
  775. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  776. preprocessRuleVar);
  777. commands.push_back(std::move(cmd));
  778. }
  779. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  780. relativeObjI, force_depends,
  781. commands, false);
  782. }
  783. if (do_assembly_rules) {
  784. commands.clear();
  785. std::string relativeObjS = relativeObjBase + ".s";
  786. std::string objS = objBase + ".s";
  787. std::string assemblyEcho =
  788. cmStrCat("Compiling ", lang, " source to assembly ", objS);
  789. this->LocalGenerator->AppendEcho(
  790. commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  791. std::string assemblyRuleVar =
  792. cmStrCat("CMAKE_", lang, "_CREATE_ASSEMBLY_SOURCE");
  793. if (const char* assemblyRule =
  794. this->Makefile->GetDefinition(assemblyRuleVar)) {
  795. std::vector<std::string> assemblyCommands =
  796. cmExpandedList(assemblyRule);
  797. std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
  798. objS, cmOutputConverter::SHELL);
  799. vars.AssemblySource = shellObjS.c_str();
  800. // Expand placeholders in the commands.
  801. for (std::string& assemblyCommand : assemblyCommands) {
  802. // no launcher for assembly commands
  803. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  804. assemblyCommand, vars);
  805. }
  806. this->LocalGenerator->CreateCDCommand(
  807. assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  808. this->LocalGenerator->GetBinaryDirectory());
  809. cmAppend(commands, assemblyCommands);
  810. } else {
  811. std::string cmd =
  812. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  813. assemblyRuleVar);
  814. commands.push_back(std::move(cmd));
  815. }
  816. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  817. relativeObjS, force_depends,
  818. commands, false);
  819. }
  820. }
  821. }
  822. void cmMakefileTargetGenerator::WriteTargetCleanRules()
  823. {
  824. std::vector<std::string> depends;
  825. std::vector<std::string> commands;
  826. // Construct the clean target name.
  827. std::string cleanTarget = cmStrCat(
  828. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  829. "/clean");
  830. // Construct the clean command.
  831. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles,
  832. this->GeneratorTarget);
  833. this->LocalGenerator->CreateCDCommand(
  834. commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  835. this->LocalGenerator->GetBinaryDirectory());
  836. // Write the rule.
  837. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  838. cleanTarget, depends, commands, true);
  839. }
  840. bool cmMakefileTargetGenerator::WriteMakeRule(
  841. std::ostream& os, const char* comment,
  842. const std::vector<std::string>& outputs,
  843. const std::vector<std::string>& depends,
  844. const std::vector<std::string>& commands, bool in_help)
  845. {
  846. bool symbolic = false;
  847. if (outputs.empty()) {
  848. return symbolic;
  849. }
  850. // Check whether we need to bother checking for a symbolic output.
  851. bool need_symbolic = this->GlobalGenerator->GetNeedSymbolicMark();
  852. // Check whether the first output is marked as symbolic.
  853. if (need_symbolic) {
  854. if (cmSourceFile* sf = this->Makefile->GetSource(outputs[0])) {
  855. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  856. }
  857. }
  858. // We always attach the actual commands to the first output.
  859. this->LocalGenerator->WriteMakeRule(os, comment, outputs[0], depends,
  860. commands, symbolic, in_help);
  861. // For single outputs, we are done.
  862. if (outputs.size() == 1) {
  863. return symbolic;
  864. }
  865. // For multiple outputs, make the extra ones depend on the first one.
  866. std::vector<std::string> const output_depends(1, outputs[0]);
  867. std::string binDir = this->LocalGenerator->GetBinaryDirectory();
  868. for (std::string const& output : cmMakeRange(outputs).advance(1)) {
  869. // Touch the extra output so "make" knows that it was updated,
  870. // but only if the output was actually created.
  871. std::string const out = this->LocalGenerator->ConvertToOutputFormat(
  872. this->LocalGenerator->MaybeConvertToRelativePath(binDir, output),
  873. cmOutputConverter::SHELL);
  874. std::vector<std::string> output_commands;
  875. bool o_symbolic = false;
  876. if (need_symbolic) {
  877. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  878. o_symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  879. }
  880. }
  881. symbolic = symbolic && o_symbolic;
  882. if (!o_symbolic) {
  883. output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
  884. }
  885. this->LocalGenerator->WriteMakeRule(os, nullptr, output, output_depends,
  886. output_commands, o_symbolic, in_help);
  887. if (!o_symbolic) {
  888. // At build time, remove the first output if this one does not exist
  889. // so that "make" will rerun the real commands that create this one.
  890. MultipleOutputPairsType::value_type p(output, outputs[0]);
  891. this->MultipleOutputPairs.insert(p);
  892. }
  893. }
  894. return symbolic;
  895. }
  896. void cmMakefileTargetGenerator::WriteTargetDependRules()
  897. {
  898. // must write the targets depend info file
  899. std::string dir =
  900. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  901. this->InfoFileNameFull = cmStrCat(dir, "/DependInfo.cmake");
  902. this->InfoFileNameFull =
  903. this->LocalGenerator->ConvertToFullPath(this->InfoFileNameFull);
  904. this->InfoFileStream = new cmGeneratedFileStream(this->InfoFileNameFull);
  905. if (!this->InfoFileStream) {
  906. return;
  907. }
  908. this->InfoFileStream->SetCopyIfDifferent(true);
  909. this->LocalGenerator->WriteDependLanguageInfo(*this->InfoFileStream,
  910. this->GeneratorTarget);
  911. // Store multiple output pairs in the depend info file.
  912. if (!this->MultipleOutputPairs.empty()) {
  913. /* clang-format off */
  914. *this->InfoFileStream
  915. << "\n"
  916. << "# Pairs of files generated by the same build rule.\n"
  917. << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
  918. /* clang-format on */
  919. for (auto const& pi : this->MultipleOutputPairs) {
  920. *this->InfoFileStream
  921. << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
  922. << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
  923. }
  924. *this->InfoFileStream << " )\n\n";
  925. }
  926. // Store list of targets linked directly or transitively.
  927. {
  928. /* clang-format off */
  929. *this->InfoFileStream
  930. << "\n"
  931. << "# Targets to which this target links.\n"
  932. << "set(CMAKE_TARGET_LINKED_INFO_FILES\n";
  933. /* clang-format on */
  934. std::vector<std::string> dirs = this->GetLinkedTargetDirectories();
  935. for (std::string const& d : dirs) {
  936. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  937. }
  938. *this->InfoFileStream << " )\n";
  939. }
  940. std::string const& working_dir =
  941. this->LocalGenerator->GetCurrentBinaryDirectory();
  942. /* clang-format off */
  943. *this->InfoFileStream
  944. << "\n"
  945. << "# Fortran module output directory.\n"
  946. << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
  947. << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
  948. << "\")\n";
  949. /* clang-format on */
  950. // and now write the rule to use it
  951. std::vector<std::string> depends;
  952. std::vector<std::string> commands;
  953. // Construct the name of the dependency generation target.
  954. std::string depTarget = cmStrCat(
  955. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  956. "/depend");
  957. // Add a command to call CMake to scan dependencies. CMake will
  958. // touch the corresponding depends file after scanning dependencies.
  959. std::ostringstream depCmd;
  960. // TODO: Account for source file properties and directory-level
  961. // definitions when scanning for dependencies.
  962. #if !defined(_WIN32) || defined(__CYGWIN__)
  963. // This platform supports symlinks, so cmSystemTools will translate
  964. // paths. Make sure PWD is set to the original name of the home
  965. // output directory to help cmSystemTools to create the same
  966. // translation table for the dependency scanning process.
  967. depCmd << "cd "
  968. << (this->LocalGenerator->ConvertToOutputFormat(
  969. cmSystemTools::CollapseFullPath(
  970. this->LocalGenerator->GetBinaryDirectory()),
  971. cmOutputConverter::SHELL))
  972. << " && ";
  973. #endif
  974. // Generate a call this signature:
  975. //
  976. // cmake -E cmake_depends <generator>
  977. // <home-src-dir> <start-src-dir>
  978. // <home-out-dir> <start-out-dir>
  979. // <dep-info> --color=$(COLOR)
  980. //
  981. // This gives the dependency scanner enough information to recreate
  982. // the state of our local generator sufficiently for its needs.
  983. depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
  984. << this->GlobalGenerator->GetName() << "\" "
  985. << this->LocalGenerator->ConvertToOutputFormat(
  986. cmSystemTools::CollapseFullPath(
  987. this->LocalGenerator->GetSourceDirectory()),
  988. cmOutputConverter::SHELL)
  989. << " "
  990. << this->LocalGenerator->ConvertToOutputFormat(
  991. cmSystemTools::CollapseFullPath(
  992. this->LocalGenerator->GetCurrentSourceDirectory()),
  993. cmOutputConverter::SHELL)
  994. << " "
  995. << this->LocalGenerator->ConvertToOutputFormat(
  996. cmSystemTools::CollapseFullPath(
  997. this->LocalGenerator->GetBinaryDirectory()),
  998. cmOutputConverter::SHELL)
  999. << " "
  1000. << this->LocalGenerator->ConvertToOutputFormat(
  1001. cmSystemTools::CollapseFullPath(
  1002. this->LocalGenerator->GetCurrentBinaryDirectory()),
  1003. cmOutputConverter::SHELL)
  1004. << " "
  1005. << this->LocalGenerator->ConvertToOutputFormat(
  1006. cmSystemTools::CollapseFullPath(this->InfoFileNameFull),
  1007. cmOutputConverter::SHELL);
  1008. if (this->LocalGenerator->GetColorMakefile()) {
  1009. depCmd << " --color=$(COLOR)";
  1010. }
  1011. commands.push_back(depCmd.str());
  1012. // Make sure all custom command outputs in this target are built.
  1013. if (this->CustomCommandDriver == OnDepends) {
  1014. this->DriveCustomCommands(depends);
  1015. }
  1016. // Write the rule.
  1017. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1018. depTarget, depends, commands, true);
  1019. }
  1020. void cmMakefileTargetGenerator::DriveCustomCommands(
  1021. std::vector<std::string>& depends)
  1022. {
  1023. // Depend on all custom command outputs.
  1024. std::vector<cmSourceFile*> sources;
  1025. this->GeneratorTarget->GetSourceFiles(
  1026. sources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  1027. for (cmSourceFile* source : sources) {
  1028. if (cmCustomCommand* cc = source->GetCustomCommand()) {
  1029. cmCustomCommandGenerator ccg(*cc, this->ConfigName,
  1030. this->LocalGenerator);
  1031. cmAppend(depends, ccg.GetOutputs());
  1032. }
  1033. }
  1034. }
  1035. void cmMakefileTargetGenerator::WriteObjectDependRules(
  1036. cmSourceFile const& source, std::vector<std::string>& depends)
  1037. {
  1038. // Create the list of dependencies known at cmake time. These are
  1039. // shared between the object file and dependency scanning rule.
  1040. depends.push_back(source.GetFullPath());
  1041. if (const char* objectDeps = source.GetProperty("OBJECT_DEPENDS")) {
  1042. cmExpandList(objectDeps, depends);
  1043. }
  1044. }
  1045. void cmMakefileTargetGenerator::GenerateCustomRuleFile(
  1046. cmCustomCommandGenerator const& ccg)
  1047. {
  1048. // Collect the commands.
  1049. std::vector<std::string> commands;
  1050. std::string comment = this->LocalGenerator->ConstructComment(ccg);
  1051. if (!comment.empty()) {
  1052. // add in a progress call if needed
  1053. this->NumberOfProgressActions++;
  1054. if (!this->NoRuleMessages) {
  1055. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  1056. this->MakeEchoProgress(progress);
  1057. this->LocalGenerator->AppendEcho(
  1058. commands, comment, cmLocalUnixMakefileGenerator3::EchoGenerate,
  1059. &progress);
  1060. }
  1061. }
  1062. // Now append the actual user-specified commands.
  1063. std::ostringstream content;
  1064. this->LocalGenerator->AppendCustomCommand(
  1065. commands, ccg, this->GeneratorTarget,
  1066. this->LocalGenerator->GetBinaryDirectory(), false, &content);
  1067. // Collect the dependencies.
  1068. std::vector<std::string> depends;
  1069. this->LocalGenerator->AppendCustomDepend(depends, ccg);
  1070. // Write the rule.
  1071. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1072. bool symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs,
  1073. depends, commands);
  1074. // If the rule has changed make sure the output is rebuilt.
  1075. if (!symbolic) {
  1076. this->GlobalGenerator->AddRuleHash(ccg.GetOutputs(), content.str());
  1077. }
  1078. // Setup implicit dependency scanning.
  1079. for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
  1080. std::string objFullPath = cmSystemTools::CollapseFullPath(outputs[0]);
  1081. std::string srcFullPath = cmSystemTools::CollapseFullPath(idi.second);
  1082. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
  1083. objFullPath, srcFullPath);
  1084. }
  1085. }
  1086. void cmMakefileTargetGenerator::MakeEchoProgress(
  1087. cmLocalUnixMakefileGenerator3::EchoProgress& progress) const
  1088. {
  1089. progress.Dir =
  1090. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), "/CMakeFiles");
  1091. std::ostringstream progressArg;
  1092. progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")";
  1093. progress.Arg = progressArg.str();
  1094. }
  1095. void cmMakefileTargetGenerator::WriteObjectsVariable(
  1096. std::string& variableName, std::string& variableNameExternal,
  1097. bool useWatcomQuote)
  1098. {
  1099. // Write a make variable assignment that lists all objects for the
  1100. // target.
  1101. variableName = this->LocalGenerator->CreateMakeVariable(
  1102. this->GeneratorTarget->GetName(), "_OBJECTS");
  1103. *this->BuildFileStream << "# Object files for target "
  1104. << this->GeneratorTarget->GetName() << "\n"
  1105. << variableName << " =";
  1106. std::string object;
  1107. const char* lineContinue =
  1108. this->Makefile->GetDefinition("CMAKE_MAKE_LINE_CONTINUE");
  1109. if (!lineContinue) {
  1110. lineContinue = "\\";
  1111. }
  1112. const char* pchExtension =
  1113. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1114. for (std::string const& obj : this->Objects) {
  1115. if (cmSystemTools::StringEndsWith(obj, pchExtension)) {
  1116. continue;
  1117. }
  1118. *this->BuildFileStream << " " << lineContinue << "\n";
  1119. *this->BuildFileStream
  1120. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1121. obj, useWatcomQuote);
  1122. }
  1123. *this->BuildFileStream << "\n";
  1124. // Write a make variable assignment that lists all external objects
  1125. // for the target.
  1126. variableNameExternal = this->LocalGenerator->CreateMakeVariable(
  1127. this->GeneratorTarget->GetName(), "_EXTERNAL_OBJECTS");
  1128. /* clang-format off */
  1129. *this->BuildFileStream
  1130. << "\n"
  1131. << "# External object files for target "
  1132. << this->GeneratorTarget->GetName() << "\n"
  1133. << variableNameExternal << " =";
  1134. /* clang-format on */
  1135. std::string currentBinDir =
  1136. this->LocalGenerator->GetCurrentBinaryDirectory();
  1137. for (std::string const& obj : this->ExternalObjects) {
  1138. object =
  1139. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, obj);
  1140. *this->BuildFileStream << " " << lineContinue << "\n";
  1141. *this->BuildFileStream
  1142. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1143. obj, useWatcomQuote);
  1144. }
  1145. *this->BuildFileStream << "\n"
  1146. << "\n";
  1147. }
  1148. class cmMakefileTargetGeneratorObjectStrings
  1149. {
  1150. public:
  1151. cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
  1152. cmOutputConverter* outputConverter,
  1153. cmStateDirectory const& stateDir,
  1154. std::string::size_type limit)
  1155. : Strings(strings)
  1156. , OutputConverter(outputConverter)
  1157. , StateDir(stateDir)
  1158. , LengthLimit(limit)
  1159. {
  1160. this->Space = "";
  1161. }
  1162. void Feed(std::string const& obj)
  1163. {
  1164. // Construct the name of the next object.
  1165. this->NextObject = this->OutputConverter->ConvertToOutputFormat(
  1166. this->MaybeConvertToRelativePath(obj), cmOutputConverter::RESPONSE);
  1167. // Roll over to next string if the limit will be exceeded.
  1168. if (this->LengthLimit != std::string::npos &&
  1169. (this->CurrentString.length() + 1 + this->NextObject.length() >
  1170. this->LengthLimit)) {
  1171. this->Strings.push_back(this->CurrentString);
  1172. this->CurrentString.clear();
  1173. this->Space = "";
  1174. }
  1175. // Separate from previous object.
  1176. this->CurrentString += this->Space;
  1177. this->Space = " ";
  1178. // Append this object.
  1179. this->CurrentString += this->NextObject;
  1180. }
  1181. void Done() { this->Strings.push_back(this->CurrentString); }
  1182. private:
  1183. std::string MaybeConvertToRelativePath(std::string const& obj)
  1184. {
  1185. if (!this->StateDir.ContainsBoth(this->StateDir.GetCurrentBinary(), obj)) {
  1186. return obj;
  1187. }
  1188. return cmSystemTools::ForceToRelativePath(
  1189. this->StateDir.GetCurrentBinary(), obj);
  1190. }
  1191. std::vector<std::string>& Strings;
  1192. cmOutputConverter* OutputConverter;
  1193. cmStateDirectory StateDir;
  1194. std::string::size_type LengthLimit;
  1195. std::string CurrentString;
  1196. std::string NextObject;
  1197. const char* Space;
  1198. };
  1199. void cmMakefileTargetGenerator::WriteObjectsStrings(
  1200. std::vector<std::string>& objStrings, std::string::size_type limit)
  1201. {
  1202. const char* pchExtension =
  1203. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1204. cmMakefileTargetGeneratorObjectStrings helper(
  1205. objStrings, this->LocalGenerator,
  1206. this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
  1207. for (std::string const& obj : this->Objects) {
  1208. if (cmSystemTools::StringEndsWith(obj, pchExtension)) {
  1209. continue;
  1210. }
  1211. helper.Feed(obj);
  1212. }
  1213. for (std::string const& obj : this->ExternalObjects) {
  1214. helper.Feed(obj);
  1215. }
  1216. helper.Done();
  1217. }
  1218. void cmMakefileTargetGenerator::WriteTargetDriverRule(
  1219. const std::string& main_output, bool relink)
  1220. {
  1221. // Compute the name of the driver target.
  1222. std::string dir =
  1223. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  1224. std::string buildTargetRuleName =
  1225. cmStrCat(dir, relink ? "/preinstall" : "/build");
  1226. buildTargetRuleName = this->LocalGenerator->MaybeConvertToRelativePath(
  1227. this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName);
  1228. // Build the list of target outputs to drive.
  1229. std::vector<std::string> depends;
  1230. depends.push_back(main_output);
  1231. const char* comment = nullptr;
  1232. if (relink) {
  1233. // Setup the comment for the preinstall driver.
  1234. comment = "Rule to relink during preinstall.";
  1235. } else {
  1236. // Setup the comment for the main build driver.
  1237. comment = "Rule to build all files generated by this target.";
  1238. // Make sure all custom command outputs in this target are built.
  1239. if (this->CustomCommandDriver == OnBuild) {
  1240. this->DriveCustomCommands(depends);
  1241. }
  1242. // Make sure the extra files are built.
  1243. cmAppend(depends, this->ExtraFiles);
  1244. }
  1245. // Write the driver rule.
  1246. std::vector<std::string> no_commands;
  1247. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, comment,
  1248. buildTargetRuleName, depends,
  1249. no_commands, true);
  1250. }
  1251. void cmMakefileTargetGenerator::AppendTargetDepends(
  1252. std::vector<std::string>& depends)
  1253. {
  1254. // Static libraries never depend on anything for linking.
  1255. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  1256. return;
  1257. }
  1258. // Loop over all library dependencies.
  1259. const std::string& cfg = this->LocalGenerator->GetConfigName();
  1260. if (cmComputeLinkInformation* cli =
  1261. this->GeneratorTarget->GetLinkInformation(cfg)) {
  1262. cmAppend(depends, cli->GetDepends());
  1263. }
  1264. }
  1265. void cmMakefileTargetGenerator::AppendObjectDepends(
  1266. std::vector<std::string>& depends)
  1267. {
  1268. // Add dependencies on the compiled object files.
  1269. std::string const& relPath =
  1270. this->LocalGenerator->GetHomeRelativeOutputPath();
  1271. for (std::string const& obj : this->Objects) {
  1272. std::string objTarget = cmStrCat(relPath, obj);
  1273. depends.push_back(std::move(objTarget));
  1274. }
  1275. // Add dependencies on the external object files.
  1276. cmAppend(depends, this->ExternalObjects);
  1277. // Add a dependency on the rule file itself.
  1278. this->LocalGenerator->AppendRuleDepend(depends,
  1279. this->BuildFileNameFull.c_str());
  1280. }
  1281. void cmMakefileTargetGenerator::AppendLinkDepends(
  1282. std::vector<std::string>& depends, const std::string& linkLanguage)
  1283. {
  1284. this->AppendObjectDepends(depends);
  1285. // Add dependencies on targets that must be built first.
  1286. this->AppendTargetDepends(depends);
  1287. // Add a dependency on the link definitions file, if any.
  1288. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1289. this->GeneratorTarget->GetModuleDefinitionInfo(
  1290. this->GetConfigName())) {
  1291. for (cmSourceFile const* src : mdi->Sources) {
  1292. depends.push_back(src->GetFullPath());
  1293. }
  1294. }
  1295. // Add a dependency on user-specified manifest files, if any.
  1296. std::vector<cmSourceFile const*> manifest_srcs;
  1297. this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
  1298. for (cmSourceFile const* manifest_src : manifest_srcs) {
  1299. depends.push_back(manifest_src->GetFullPath());
  1300. }
  1301. // Add user-specified dependencies.
  1302. this->GeneratorTarget->GetLinkDepends(depends, this->ConfigName,
  1303. linkLanguage);
  1304. }
  1305. std::string cmMakefileTargetGenerator::GetLinkRule(
  1306. const std::string& linkRuleVar)
  1307. {
  1308. std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar);
  1309. if (this->GeneratorTarget->HasImplibGNUtoMS(this->ConfigName)) {
  1310. std::string ruleVar = cmStrCat(
  1311. "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName),
  1312. "_GNUtoMS_RULE");
  1313. if (const char* rule = this->Makefile->GetDefinition(ruleVar)) {
  1314. linkRule += rule;
  1315. }
  1316. }
  1317. return linkRule;
  1318. }
  1319. void cmMakefileTargetGenerator::CloseFileStreams()
  1320. {
  1321. delete this->BuildFileStream;
  1322. delete this->InfoFileStream;
  1323. delete this->FlagFileStream;
  1324. }
  1325. void cmMakefileTargetGenerator::CreateLinkScript(
  1326. const char* name, std::vector<std::string> const& link_commands,
  1327. std::vector<std::string>& makefile_commands,
  1328. std::vector<std::string>& makefile_depends)
  1329. {
  1330. // Create the link script file.
  1331. std::string linkScriptName =
  1332. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1333. cmGeneratedFileStream linkScriptStream(linkScriptName);
  1334. linkScriptStream.SetCopyIfDifferent(true);
  1335. for (std::string const& link_command : link_commands) {
  1336. // Do not write out empty commands or commands beginning in the
  1337. // shell no-op ":".
  1338. if (!link_command.empty() && link_command[0] != ':') {
  1339. linkScriptStream << link_command << "\n";
  1340. }
  1341. }
  1342. // Create the makefile command to invoke the link script.
  1343. std::string link_command = cmStrCat(
  1344. "$(CMAKE_COMMAND) -E cmake_link_script ",
  1345. this->LocalGenerator->ConvertToOutputFormat(
  1346. this->LocalGenerator->MaybeConvertToRelativePath(
  1347. this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName),
  1348. cmOutputConverter::SHELL),
  1349. " --verbose=$(VERBOSE)");
  1350. makefile_commands.push_back(std::move(link_command));
  1351. makefile_depends.push_back(std::move(linkScriptName));
  1352. }
  1353. bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
  1354. std::string const& l) const
  1355. {
  1356. // Check for an explicit setting one way or the other.
  1357. std::string const responseVar =
  1358. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
  1359. if (const char* val = this->Makefile->GetDefinition(responseVar)) {
  1360. if (*val) {
  1361. return cmIsOn(val);
  1362. }
  1363. }
  1364. // Check for a system limit.
  1365. if (size_t const limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  1366. // Compute the total length of our list of object files with room
  1367. // for argument separation and quoting. This does not convert paths
  1368. // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so the
  1369. // actual list will likely be much shorter than this. However, in the
  1370. // worst case all objects will remain as absolute paths.
  1371. size_t length = 0;
  1372. for (std::string const& obj : this->Objects) {
  1373. length += obj.size() + 3;
  1374. }
  1375. for (std::string const& ext_obj : this->ExternalObjects) {
  1376. length += ext_obj.size() + 3;
  1377. }
  1378. // We need to guarantee room for both objects and libraries, so
  1379. // if the objects take up more than half then use a response file
  1380. // for them.
  1381. if (length > (limit / 2)) {
  1382. return true;
  1383. }
  1384. }
  1385. // We do not need a response file for objects.
  1386. return false;
  1387. }
  1388. bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
  1389. std::string const& l) const
  1390. {
  1391. // Check for an explicit setting one way or the other.
  1392. std::string const responseVar =
  1393. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  1394. if (const char* val = this->Makefile->GetDefinition(responseVar)) {
  1395. if (*val) {
  1396. return cmIsOn(val);
  1397. }
  1398. }
  1399. // We do not need a response file for libraries.
  1400. return false;
  1401. }
  1402. std::string cmMakefileTargetGenerator::CreateResponseFile(
  1403. const char* name, std::string const& options,
  1404. std::vector<std::string>& makefile_depends)
  1405. {
  1406. // Create the response file.
  1407. std::string responseFileNameFull =
  1408. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1409. cmGeneratedFileStream responseStream(responseFileNameFull);
  1410. responseStream.SetCopyIfDifferent(true);
  1411. responseStream << options << "\n";
  1412. // Add a dependency so the target will rebuild when the set of
  1413. // objects changes.
  1414. makefile_depends.push_back(std::move(responseFileNameFull));
  1415. // Construct the name to be used on the command line.
  1416. std::string responseFileName =
  1417. cmStrCat(this->TargetBuildDirectory, '/', name);
  1418. return responseFileName;
  1419. }
  1420. cmLinkLineComputer* cmMakefileTargetGenerator::CreateLinkLineComputer(
  1421. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir)
  1422. {
  1423. if (this->Makefile->IsOn("MSVC60")) {
  1424. return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
  1425. stateDir);
  1426. }
  1427. return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
  1428. stateDir);
  1429. }
  1430. void cmMakefileTargetGenerator::CreateLinkLibs(
  1431. cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
  1432. bool useResponseFile, std::vector<std::string>& makefile_depends)
  1433. {
  1434. std::string frameworkPath;
  1435. std::string linkPath;
  1436. const std::string& config =
  1437. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1438. cmComputeLinkInformation* pcli =
  1439. this->GeneratorTarget->GetLinkInformation(config);
  1440. this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1441. frameworkPath, linkPath);
  1442. linkLibs = frameworkPath + linkPath + linkLibs;
  1443. if (useResponseFile &&
  1444. linkLibs.find_first_not_of(' ') != std::string::npos) {
  1445. // Lookup the response file reference flag.
  1446. std::string responseFlagVar = cmStrCat(
  1447. "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName),
  1448. "_RESPONSE_FILE_LINK_FLAG");
  1449. const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar);
  1450. if (!responseFlag) {
  1451. responseFlag = "@";
  1452. }
  1453. // Create this response file.
  1454. std::string link_rsp =
  1455. this->CreateResponseFile("linklibs.rsp", linkLibs, makefile_depends);
  1456. // Reference the response file.
  1457. linkLibs = cmStrCat(responseFlag,
  1458. this->LocalGenerator->ConvertToOutputFormat(
  1459. link_rsp, cmOutputConverter::SHELL));
  1460. }
  1461. }
  1462. void cmMakefileTargetGenerator::CreateObjectLists(
  1463. bool useLinkScript, bool useArchiveRules, bool useResponseFile,
  1464. std::string& buildObjs, std::vector<std::string>& makefile_depends,
  1465. bool useWatcomQuote)
  1466. {
  1467. std::string variableName;
  1468. std::string variableNameExternal;
  1469. this->WriteObjectsVariable(variableName, variableNameExternal,
  1470. useWatcomQuote);
  1471. if (useResponseFile) {
  1472. // MSVC response files cannot exceed 128K.
  1473. std::string::size_type const responseFileLimit = 131000;
  1474. // Construct the individual object list strings.
  1475. std::vector<std::string> object_strings;
  1476. this->WriteObjectsStrings(object_strings, responseFileLimit);
  1477. // Lookup the response file reference flag.
  1478. std::string responseFlagVar = cmStrCat(
  1479. "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName),
  1480. "_RESPONSE_FILE_LINK_FLAG");
  1481. const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar);
  1482. if (!responseFlag) {
  1483. responseFlag = "@";
  1484. }
  1485. // Write a response file for each string.
  1486. const char* sep = "";
  1487. for (unsigned int i = 0; i < object_strings.size(); ++i) {
  1488. // Number the response files.
  1489. char rsp[32];
  1490. sprintf(rsp, "objects%u.rsp", i + 1);
  1491. // Create this response file.
  1492. std::string objects_rsp =
  1493. this->CreateResponseFile(rsp, object_strings[i], makefile_depends);
  1494. // Separate from previous response file references.
  1495. buildObjs += sep;
  1496. sep = " ";
  1497. // Reference the response file.
  1498. buildObjs += responseFlag;
  1499. buildObjs += this->LocalGenerator->ConvertToOutputFormat(
  1500. objects_rsp, cmOutputConverter::SHELL);
  1501. }
  1502. } else if (useLinkScript) {
  1503. if (!useArchiveRules) {
  1504. std::vector<std::string> objStrings;
  1505. this->WriteObjectsStrings(objStrings);
  1506. buildObjs = objStrings[0];
  1507. }
  1508. } else {
  1509. buildObjs =
  1510. cmStrCat("$(", variableName, ") $(", variableNameExternal, ')');
  1511. }
  1512. }
  1513. void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
  1514. const std::string& lang)
  1515. {
  1516. std::string responseVar =
  1517. cmStrCat("CMAKE_", lang, "_USE_RESPONSE_FILE_FOR_INCLUDES");
  1518. bool useResponseFile = this->Makefile->IsOn(responseVar);
  1519. std::vector<std::string> includes;
  1520. const std::string& config =
  1521. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1522. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1523. lang, config);
  1524. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  1525. includes, this->GeneratorTarget, lang, false, useResponseFile, config);
  1526. if (includeFlags.empty()) {
  1527. return;
  1528. }
  1529. if (useResponseFile) {
  1530. std::string const responseFlagVar =
  1531. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  1532. std::string responseFlag =
  1533. this->Makefile->GetSafeDefinition(responseFlagVar);
  1534. if (responseFlag.empty()) {
  1535. responseFlag = "@";
  1536. }
  1537. std::string name = cmStrCat("includes_", lang, ".rsp");
  1538. std::string arg = std::move(responseFlag) +
  1539. this->CreateResponseFile(name.c_str(), includeFlags,
  1540. this->FlagFileDepends[lang]);
  1541. this->LocalGenerator->AppendFlags(flags, arg);
  1542. } else {
  1543. this->LocalGenerator->AppendFlags(flags, includeFlags);
  1544. }
  1545. }
  1546. void cmMakefileTargetGenerator::GenDefFile(
  1547. std::vector<std::string>& real_link_commands)
  1548. {
  1549. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1550. this->GeneratorTarget->GetModuleDefinitionInfo(this->GetConfigName());
  1551. if (!mdi || !mdi->DefFileGenerated) {
  1552. return;
  1553. }
  1554. std::string cmd = cmSystemTools::GetCMakeCommand();
  1555. cmd = cmStrCat(
  1556. this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL),
  1557. " -E __create_def ",
  1558. this->LocalGenerator->ConvertToOutputFormat(
  1559. this->LocalGenerator->MaybeConvertToRelativePath(
  1560. this->LocalGenerator->GetCurrentBinaryDirectory(), mdi->DefFile),
  1561. cmOutputConverter::SHELL),
  1562. ' ');
  1563. std::string objlist_file = mdi->DefFile + ".objs";
  1564. cmd += this->LocalGenerator->ConvertToOutputFormat(
  1565. this->LocalGenerator->MaybeConvertToRelativePath(
  1566. this->LocalGenerator->GetCurrentBinaryDirectory(), objlist_file),
  1567. cmOutputConverter::SHELL);
  1568. real_link_commands.insert(real_link_commands.begin(), cmd);
  1569. // create a list of obj files for the -E __create_def to read
  1570. cmGeneratedFileStream fout(objlist_file);
  1571. if (mdi->WindowsExportAllSymbols) {
  1572. for (std::string const& obj : this->Objects) {
  1573. if (cmHasLiteralSuffix(obj, ".obj")) {
  1574. fout << obj << "\n";
  1575. }
  1576. }
  1577. for (std::string const& obj : this->ExternalObjects) {
  1578. fout << obj << "\n";
  1579. }
  1580. }
  1581. for (cmSourceFile const* src : mdi->Sources) {
  1582. fout << src->GetFullPath() << "\n";
  1583. }
  1584. }