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