cmMakefileTargetGenerator.cxx 69 KB

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