cmMakefileTargetGenerator.cxx 69 KB

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