cmMakefileTargetGenerator.cxx 67 KB

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