cmMakefileTargetGenerator.cxx 67 KB

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