cmMakefileTargetGenerator.cxx 71 KB

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