cmCoreTryCompile.cxx 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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 "cmCoreTryCompile.h"
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <set>
  7. #include <sstream>
  8. #include <utility>
  9. #include <cm/string_view>
  10. #include <cmext/string_view>
  11. #include "cmsys/Directory.hxx"
  12. #include "cmExportTryCompileFileGenerator.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmMakefile.h"
  15. #include "cmMessageType.h"
  16. #include "cmOutputConverter.h"
  17. #include "cmPolicies.h"
  18. #include "cmState.h"
  19. #include "cmStringAlgorithms.h"
  20. #include "cmSystemTools.h"
  21. #include "cmTarget.h"
  22. #include "cmValue.h"
  23. #include "cmVersion.h"
  24. #include "cmake.h"
  25. namespace {
  26. class LanguageStandardState
  27. {
  28. public:
  29. LanguageStandardState(std::string&& lang)
  30. : IsEnabled(false)
  31. , DidStandard(false)
  32. , DidStandardRequired(false)
  33. , DidExtensions(false)
  34. , StandardFlag(lang + "_STANDARD")
  35. , RequiredFlag(lang + "_STANDARD_REQUIRED")
  36. , ExtensionFlag(lang + "_EXTENSIONS")
  37. {
  38. }
  39. void Enabled(bool isEnabled) { this->IsEnabled = isEnabled; }
  40. bool UpdateIfMatches(std::vector<std::string> const& argv, size_t& index)
  41. {
  42. bool updated = false;
  43. if (argv[index] == this->StandardFlag) {
  44. this->DidStandard = true;
  45. this->StandardValue = argv[++index];
  46. updated = true;
  47. } else if (argv[index] == this->RequiredFlag) {
  48. this->DidStandardRequired = true;
  49. this->RequiredValue = argv[++index];
  50. updated = true;
  51. } else if (argv[index] == this->ExtensionFlag) {
  52. this->DidExtensions = true;
  53. this->ExtensionValue = argv[++index];
  54. updated = true;
  55. }
  56. return updated;
  57. }
  58. bool Validate(cmMakefile* const makefile) const
  59. {
  60. if (this->DidStandard) {
  61. makefile->IssueMessage(
  62. MessageType::FATAL_ERROR,
  63. cmStrCat(this->StandardFlag,
  64. " allowed only in source file signature."));
  65. return false;
  66. }
  67. if (this->DidStandardRequired) {
  68. makefile->IssueMessage(
  69. MessageType::FATAL_ERROR,
  70. cmStrCat(this->RequiredFlag,
  71. " allowed only in source file signature."));
  72. return false;
  73. }
  74. if (this->DidExtensions) {
  75. makefile->IssueMessage(
  76. MessageType::FATAL_ERROR,
  77. cmStrCat(this->ExtensionFlag,
  78. " allowed only in source file signature."));
  79. return false;
  80. }
  81. return true;
  82. }
  83. bool DidNone() const
  84. {
  85. return !this->DidStandard && !this->DidStandardRequired &&
  86. !this->DidExtensions;
  87. }
  88. void LoadUnsetPropertyValues(cmMakefile* const makefile, bool honorStandard,
  89. bool warnCMP0067,
  90. std::vector<std::string>& warnCMP0067Variables)
  91. {
  92. if (!this->IsEnabled) {
  93. return;
  94. }
  95. auto lookupStdVar = [&](std::string const& var) -> std::string {
  96. std::string value = makefile->GetSafeDefinition(var);
  97. if (warnCMP0067 && !value.empty()) {
  98. value.clear();
  99. warnCMP0067Variables.emplace_back(var);
  100. }
  101. return value;
  102. };
  103. if (honorStandard || warnCMP0067) {
  104. if (!this->DidStandard) {
  105. this->StandardValue =
  106. lookupStdVar(cmStrCat("CMAKE_", this->StandardFlag));
  107. }
  108. if (!this->DidStandardRequired) {
  109. this->RequiredValue =
  110. lookupStdVar(cmStrCat("CMAKE_", this->RequiredFlag));
  111. }
  112. if (!this->DidExtensions) {
  113. this->ExtensionValue =
  114. lookupStdVar(cmStrCat("CMAKE_", this->ExtensionFlag));
  115. }
  116. }
  117. }
  118. void WriteProperties(FILE* fout, std::string const& targetName) const
  119. {
  120. if (!this->IsEnabled) {
  121. return;
  122. }
  123. auto writeProp = [&](std::string const& prop, std::string const& value) {
  124. fprintf(fout, "set_property(TARGET %s PROPERTY %s %s)\n",
  125. targetName.c_str(),
  126. cmOutputConverter::EscapeForCMake(prop).c_str(),
  127. cmOutputConverter::EscapeForCMake(value).c_str());
  128. };
  129. if (!this->StandardValue.empty()) {
  130. writeProp(this->StandardFlag, this->StandardValue);
  131. }
  132. if (!this->RequiredValue.empty()) {
  133. writeProp(this->RequiredFlag, this->RequiredValue);
  134. }
  135. if (!this->ExtensionValue.empty()) {
  136. writeProp(this->ExtensionFlag, this->ExtensionValue);
  137. }
  138. }
  139. private:
  140. bool IsEnabled;
  141. bool DidStandard;
  142. bool DidStandardRequired;
  143. bool DidExtensions;
  144. std::string StandardFlag;
  145. std::string RequiredFlag;
  146. std::string ExtensionFlag;
  147. std::string StandardValue;
  148. std::string RequiredValue;
  149. std::string ExtensionValue;
  150. };
  151. constexpr size_t lang_property_start = 0;
  152. constexpr size_t lang_property_size = 4;
  153. constexpr size_t pie_property_start = 4;
  154. constexpr size_t pie_property_size = 2;
  155. #define SETUP_LANGUAGE(name, lang) \
  156. static const std::string name[lang_property_size + pie_property_size + 1] = \
  157. { "CMAKE_" #lang "_COMPILER_EXTERNAL_TOOLCHAIN", \
  158. "CMAKE_" #lang "_COMPILER_TARGET", \
  159. "CMAKE_" #lang "_LINK_NO_PIE_SUPPORTED", \
  160. "CMAKE_" #lang "_PIE_SUPPORTED", "" }
  161. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  162. SETUP_LANGUAGE(c_properties, C);
  163. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  164. SETUP_LANGUAGE(cxx_properties, CXX);
  165. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  166. SETUP_LANGUAGE(cuda_properties, CUDA);
  167. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  168. SETUP_LANGUAGE(fortran_properties, Fortran);
  169. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  170. SETUP_LANGUAGE(hip_properties, HIP);
  171. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  172. SETUP_LANGUAGE(objc_properties, OBJC);
  173. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  174. SETUP_LANGUAGE(objcxx_properties, OBJCXX);
  175. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  176. SETUP_LANGUAGE(ispc_properties, ISPC);
  177. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  178. SETUP_LANGUAGE(swift_properties, Swift);
  179. #undef SETUP_LANGUAGE
  180. std::string const kCMAKE_CUDA_ARCHITECTURES = "CMAKE_CUDA_ARCHITECTURES";
  181. std::string const kCMAKE_CUDA_RUNTIME_LIBRARY = "CMAKE_CUDA_RUNTIME_LIBRARY";
  182. std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
  183. std::string const kCMAKE_HIP_ARCHITECTURES = "CMAKE_HIP_ARCHITECTURES";
  184. std::string const kCMAKE_HIP_RUNTIME_LIBRARY = "CMAKE_HIP_RUNTIME_LIBRARY";
  185. std::string const kCMAKE_ISPC_INSTRUCTION_SETS = "CMAKE_ISPC_INSTRUCTION_SETS";
  186. std::string const kCMAKE_ISPC_HEADER_SUFFIX = "CMAKE_ISPC_HEADER_SUFFIX";
  187. std::string const kCMAKE_LINK_SEARCH_END_STATIC =
  188. "CMAKE_LINK_SEARCH_END_STATIC";
  189. std::string const kCMAKE_LINK_SEARCH_START_STATIC =
  190. "CMAKE_LINK_SEARCH_START_STATIC";
  191. std::string const kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT =
  192. "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT";
  193. std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
  194. std::string const kCMAKE_OSX_DEPLOYMENT_TARGET = "CMAKE_OSX_DEPLOYMENT_TARGET";
  195. std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
  196. std::string const kCMAKE_APPLE_ARCH_SYSROOTS = "CMAKE_APPLE_ARCH_SYSROOTS";
  197. std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
  198. "CMAKE_POSITION_INDEPENDENT_CODE";
  199. std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
  200. std::string const kCMAKE_SYSROOT_COMPILE = "CMAKE_SYSROOT_COMPILE";
  201. std::string const kCMAKE_SYSROOT_LINK = "CMAKE_SYSROOT_LINK";
  202. std::string const kCMAKE_ARMClang_CMP0123 = "CMAKE_ARMClang_CMP0123";
  203. std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
  204. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
  205. std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
  206. "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
  207. std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
  208. std::string const kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT =
  209. "CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT";
  210. /* GHS Multi platform variables */
  211. std::set<std::string> const ghs_platform_vars{
  212. "GHS_TARGET_PLATFORM", "GHS_PRIMARY_TARGET", "GHS_TOOLSET_ROOT",
  213. "GHS_OS_ROOT", "GHS_OS_DIR", "GHS_BSP_NAME",
  214. "GHS_OS_DIR_OPTION"
  215. };
  216. }
  217. int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
  218. bool isTryRun)
  219. {
  220. this->BinaryDirectory = argv[1];
  221. this->OutputFile.clear();
  222. // which signature were we called with ?
  223. this->SrcFileSignature = true;
  224. cmStateEnums::TargetType targetType = cmStateEnums::EXECUTABLE;
  225. cmValue tt = this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_TARGET_TYPE");
  226. if (!isTryRun && cmNonempty(tt)) {
  227. if (*tt == cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE)) {
  228. targetType = cmStateEnums::EXECUTABLE;
  229. } else if (*tt ==
  230. cmState::GetTargetTypeName(cmStateEnums::STATIC_LIBRARY)) {
  231. targetType = cmStateEnums::STATIC_LIBRARY;
  232. } else {
  233. this->Makefile->IssueMessage(
  234. MessageType::FATAL_ERROR,
  235. cmStrCat("Invalid value '", *tt,
  236. "' for CMAKE_TRY_COMPILE_TARGET_TYPE. Only '",
  237. cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE),
  238. "' and '",
  239. cmState::GetTargetTypeName(cmStateEnums::STATIC_LIBRARY),
  240. "' are allowed."));
  241. return -1;
  242. }
  243. }
  244. std::string sourceDirectory = argv[2];
  245. std::string projectName;
  246. std::string targetName;
  247. std::vector<std::string> cmakeFlags(1, "CMAKE_FLAGS"); // fake argv[0]
  248. std::vector<std::string> compileDefs;
  249. std::string cmakeInternal;
  250. std::string outputVariable;
  251. std::string copyFile;
  252. std::string copyFileError;
  253. LanguageStandardState cState("C");
  254. LanguageStandardState cudaState("CUDA");
  255. LanguageStandardState cxxState("CXX");
  256. LanguageStandardState hipState("HIP");
  257. LanguageStandardState objcState("OBJC");
  258. LanguageStandardState objcxxState("OBJCXX");
  259. std::vector<std::string> targets;
  260. std::vector<std::string> linkOptions;
  261. std::string libsToLink = " ";
  262. bool useOldLinkLibs = true;
  263. char targetNameBuf[64];
  264. bool didOutputVariable = false;
  265. bool didCopyFile = false;
  266. bool didCopyFileError = false;
  267. bool useSources = argv[2] == "SOURCES";
  268. std::vector<std::string> sources;
  269. enum Doing
  270. {
  271. DoingNone,
  272. DoingCMakeFlags,
  273. DoingCompileDefinitions,
  274. DoingLinkOptions,
  275. DoingLinkLibraries,
  276. DoingOutputVariable,
  277. DoingCopyFile,
  278. DoingCopyFileError,
  279. DoingSources,
  280. DoingCMakeInternal
  281. };
  282. Doing doing = useSources ? DoingSources : DoingNone;
  283. for (size_t i = 3; i < argv.size(); ++i) {
  284. if (argv[i] == "CMAKE_FLAGS") {
  285. doing = DoingCMakeFlags;
  286. } else if (argv[i] == "COMPILE_DEFINITIONS") {
  287. doing = DoingCompileDefinitions;
  288. } else if (argv[i] == "LINK_OPTIONS") {
  289. doing = DoingLinkOptions;
  290. } else if (argv[i] == "LINK_LIBRARIES") {
  291. doing = DoingLinkLibraries;
  292. useOldLinkLibs = false;
  293. } else if (argv[i] == "OUTPUT_VARIABLE") {
  294. doing = DoingOutputVariable;
  295. didOutputVariable = true;
  296. } else if (argv[i] == "COPY_FILE") {
  297. doing = DoingCopyFile;
  298. didCopyFile = true;
  299. } else if (argv[i] == "COPY_FILE_ERROR") {
  300. doing = DoingCopyFileError;
  301. didCopyFileError = true;
  302. } else if (cState.UpdateIfMatches(argv, i) ||
  303. cxxState.UpdateIfMatches(argv, i) ||
  304. cudaState.UpdateIfMatches(argv, i) ||
  305. hipState.UpdateIfMatches(argv, i) ||
  306. objcState.UpdateIfMatches(argv, i) ||
  307. objcxxState.UpdateIfMatches(argv, i)) {
  308. continue;
  309. } else if (argv[i] == "__CMAKE_INTERNAL") {
  310. doing = DoingCMakeInternal;
  311. } else if (doing == DoingCMakeFlags) {
  312. cmakeFlags.emplace_back(argv[i]);
  313. } else if (doing == DoingCompileDefinitions) {
  314. cmExpandList(argv[i], compileDefs);
  315. } else if (doing == DoingLinkOptions) {
  316. linkOptions.emplace_back(argv[i]);
  317. } else if (doing == DoingLinkLibraries) {
  318. libsToLink += "\"" + cmTrimWhitespace(argv[i]) + "\" ";
  319. if (cmTarget* tgt = this->Makefile->FindTargetToUse(argv[i])) {
  320. switch (tgt->GetType()) {
  321. case cmStateEnums::SHARED_LIBRARY:
  322. case cmStateEnums::STATIC_LIBRARY:
  323. case cmStateEnums::INTERFACE_LIBRARY:
  324. case cmStateEnums::UNKNOWN_LIBRARY:
  325. break;
  326. case cmStateEnums::EXECUTABLE:
  327. if (tgt->IsExecutableWithExports()) {
  328. break;
  329. }
  330. CM_FALLTHROUGH;
  331. default:
  332. this->Makefile->IssueMessage(
  333. MessageType::FATAL_ERROR,
  334. cmStrCat("Only libraries may be used as try_compile or try_run "
  335. "IMPORTED LINK_LIBRARIES. Got ",
  336. tgt->GetName(), " of type ",
  337. cmState::GetTargetTypeName(tgt->GetType()), "."));
  338. return -1;
  339. }
  340. if (tgt->IsImported()) {
  341. targets.emplace_back(argv[i]);
  342. }
  343. }
  344. } else if (doing == DoingOutputVariable) {
  345. outputVariable = argv[i];
  346. doing = DoingNone;
  347. } else if (doing == DoingCopyFile) {
  348. copyFile = argv[i];
  349. doing = DoingNone;
  350. } else if (doing == DoingCopyFileError) {
  351. copyFileError = argv[i];
  352. doing = DoingNone;
  353. } else if (doing == DoingSources) {
  354. sources.emplace_back(argv[i]);
  355. } else if (doing == DoingCMakeInternal) {
  356. cmakeInternal = argv[i];
  357. doing = DoingNone;
  358. } else if (i == 3) {
  359. this->SrcFileSignature = false;
  360. projectName = argv[i];
  361. } else if (i == 4 && !this->SrcFileSignature) {
  362. targetName = argv[i];
  363. } else {
  364. std::ostringstream m;
  365. m << "try_compile given unknown argument \"" << argv[i] << "\".";
  366. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  367. }
  368. }
  369. if (didCopyFile && copyFile.empty()) {
  370. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  371. "COPY_FILE must be followed by a file path");
  372. return -1;
  373. }
  374. if (didCopyFileError && copyFileError.empty()) {
  375. this->Makefile->IssueMessage(
  376. MessageType::FATAL_ERROR,
  377. "COPY_FILE_ERROR must be followed by a variable name");
  378. return -1;
  379. }
  380. if (didCopyFileError && !didCopyFile) {
  381. this->Makefile->IssueMessage(
  382. MessageType::FATAL_ERROR,
  383. "COPY_FILE_ERROR may be used only with COPY_FILE");
  384. return -1;
  385. }
  386. if (didOutputVariable && outputVariable.empty()) {
  387. this->Makefile->IssueMessage(
  388. MessageType::FATAL_ERROR,
  389. "OUTPUT_VARIABLE must be followed by a variable name");
  390. return -1;
  391. }
  392. if (useSources && sources.empty()) {
  393. this->Makefile->IssueMessage(
  394. MessageType::FATAL_ERROR,
  395. "SOURCES must be followed by at least one source file");
  396. return -1;
  397. }
  398. if (!this->SrcFileSignature) {
  399. if (!cState.Validate(this->Makefile)) {
  400. return -1;
  401. }
  402. if (!cudaState.Validate(this->Makefile)) {
  403. return -1;
  404. }
  405. if (!hipState.Validate(this->Makefile)) {
  406. return -1;
  407. }
  408. if (!cxxState.Validate(this->Makefile)) {
  409. return -1;
  410. }
  411. if (!objcState.Validate(this->Makefile)) {
  412. return -1;
  413. }
  414. if (!objcxxState.Validate(this->Makefile)) {
  415. return -1;
  416. }
  417. }
  418. // compute the binary dir when TRY_COMPILE is called with a src file
  419. // signature
  420. if (this->SrcFileSignature) {
  421. this->BinaryDirectory += "/CMakeFiles/CMakeTmp";
  422. } else {
  423. // only valid for srcfile signatures
  424. if (!compileDefs.empty()) {
  425. this->Makefile->IssueMessage(
  426. MessageType::FATAL_ERROR,
  427. "COMPILE_DEFINITIONS specified on a srcdir type TRY_COMPILE");
  428. return -1;
  429. }
  430. if (!copyFile.empty()) {
  431. this->Makefile->IssueMessage(
  432. MessageType::FATAL_ERROR,
  433. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  434. return -1;
  435. }
  436. }
  437. // make sure the binary directory exists
  438. cmSystemTools::MakeDirectory(this->BinaryDirectory);
  439. // do not allow recursive try Compiles
  440. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
  441. std::ostringstream e;
  442. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  443. << " " << this->BinaryDirectory << "\n";
  444. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  445. return -1;
  446. }
  447. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  448. // which signature are we using? If we are using var srcfile bindir
  449. if (this->SrcFileSignature) {
  450. // remove any CMakeCache.txt files so we will have a clean test
  451. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  452. cmSystemTools::RemoveFile(ccFile);
  453. // Choose sources.
  454. if (!useSources) {
  455. sources.emplace_back(argv[2]);
  456. }
  457. // Detect languages to enable.
  458. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  459. std::set<std::string> testLangs;
  460. for (std::string const& si : sources) {
  461. std::string ext = cmSystemTools::GetFilenameLastExtension(si);
  462. std::string lang = gg->GetLanguageFromExtension(ext.c_str());
  463. if (!lang.empty()) {
  464. testLangs.insert(lang);
  465. } else {
  466. std::ostringstream err;
  467. err << "Unknown extension \"" << ext << "\" for file\n"
  468. << " " << si << "\n"
  469. << "try_compile() works only for enabled languages. "
  470. << "Currently these are:\n ";
  471. std::vector<std::string> langs;
  472. gg->GetEnabledLanguages(langs);
  473. err << cmJoin(langs, " ");
  474. err << "\nSee project() command to enable other languages.";
  475. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, err.str());
  476. return -1;
  477. }
  478. }
  479. // when the only language is ISPC we know that the output
  480. // type must by a static library
  481. if (testLangs.size() == 1 && testLangs.count("ISPC") == 1) {
  482. targetType = cmStateEnums::STATIC_LIBRARY;
  483. }
  484. std::string const tcConfig =
  485. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  486. // we need to create a directory and CMakeLists file etc...
  487. // first create the directories
  488. sourceDirectory = this->BinaryDirectory;
  489. // now create a CMakeLists.txt file in that directory
  490. FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
  491. if (!fout) {
  492. std::ostringstream e;
  493. /* clang-format off */
  494. e << "Failed to open\n"
  495. << " " << outFileName << "\n"
  496. << cmSystemTools::GetLastSystemError();
  497. /* clang-format on */
  498. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  499. return -1;
  500. }
  501. cmValue def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  502. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  503. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  504. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  505. if (def) {
  506. fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def->c_str());
  507. }
  508. /* Set MSVC runtime library policy to match our selection. */
  509. if (cmValue msvcRuntimeLibraryDefault =
  510. this->Makefile->GetDefinition(kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)) {
  511. fprintf(fout, "cmake_policy(SET CMP0091 %s)\n",
  512. !msvcRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
  513. }
  514. /* Set Watcom runtime library policy to match our selection. */
  515. if (cmValue watcomRuntimeLibraryDefault = this->Makefile->GetDefinition(
  516. kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT)) {
  517. fprintf(fout, "cmake_policy(SET CMP0136 %s)\n",
  518. !watcomRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
  519. }
  520. /* Set CUDA architectures policy to match outer project. */
  521. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0104) !=
  522. cmPolicies::NEW &&
  523. testLangs.find("CUDA") != testLangs.end() &&
  524. this->Makefile->GetSafeDefinition(kCMAKE_CUDA_ARCHITECTURES).empty()) {
  525. fprintf(fout, "cmake_policy(SET CMP0104 OLD)\n");
  526. }
  527. /* Set ARMClang cpu/arch policy to match outer project. */
  528. if (cmValue cmp0123 =
  529. this->Makefile->GetDefinition(kCMAKE_ARMClang_CMP0123)) {
  530. fprintf(fout, "cmake_policy(SET CMP0123 %s)\n",
  531. *cmp0123 == "NEW"_s ? "NEW" : "OLD");
  532. }
  533. /* Set cache/normal variable policy to match outer project.
  534. It may affect toolchain files. */
  535. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) !=
  536. cmPolicies::NEW) {
  537. fprintf(fout, "cmake_policy(SET CMP0126 OLD)\n");
  538. }
  539. std::string projectLangs;
  540. for (std::string const& li : testLangs) {
  541. projectLangs += " " + li;
  542. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  543. std::string rulesOverrideLang = cmStrCat(rulesOverrideBase, "_", li);
  544. if (cmValue rulesOverridePath =
  545. this->Makefile->GetDefinition(rulesOverrideLang)) {
  546. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
  547. rulesOverridePath->c_str());
  548. } else if (cmValue rulesOverridePath2 =
  549. this->Makefile->GetDefinition(rulesOverrideBase)) {
  550. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
  551. rulesOverridePath2->c_str());
  552. }
  553. }
  554. fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  555. if (cmakeInternal == "ABI") {
  556. // This is the ABI detection step, also used for implicit includes.
  557. // Erase any include_directories() calls from the toolchain file so
  558. // that we do not see them as implicit. Our ABI detection source
  559. // does not include any system headers anyway.
  560. fprintf(fout,
  561. "set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES \"\")\n");
  562. }
  563. fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
  564. for (std::string const& li : testLangs) {
  565. std::string langFlags = "CMAKE_" + li + "_FLAGS";
  566. cmValue flags = this->Makefile->GetDefinition(langFlags);
  567. fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
  568. cmOutputConverter::EscapeForCMake(*flags).c_str());
  569. fprintf(fout,
  570. "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
  571. " ${COMPILE_DEFINITIONS}\")\n",
  572. li.c_str(), li.c_str());
  573. }
  574. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
  575. case cmPolicies::WARN:
  576. if (this->Makefile->PolicyOptionalWarningEnabled(
  577. "CMAKE_POLICY_WARNING_CMP0066")) {
  578. std::ostringstream w;
  579. /* clang-format off */
  580. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
  581. "For compatibility with older versions of CMake, try_compile "
  582. "is not honoring caller config-specific compiler flags "
  583. "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
  584. ;
  585. /* clang-format on */
  586. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  587. }
  588. CM_FALLTHROUGH;
  589. case cmPolicies::OLD:
  590. // OLD behavior is to do nothing.
  591. break;
  592. case cmPolicies::REQUIRED_IF_USED:
  593. case cmPolicies::REQUIRED_ALWAYS:
  594. this->Makefile->IssueMessage(
  595. MessageType::FATAL_ERROR,
  596. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0066));
  597. CM_FALLTHROUGH;
  598. case cmPolicies::NEW: {
  599. // NEW behavior is to pass config-specific compiler flags.
  600. static std::string const cfgDefault = "DEBUG";
  601. std::string const cfg =
  602. !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
  603. for (std::string const& li : testLangs) {
  604. std::string const langFlagsCfg =
  605. cmStrCat("CMAKE_", li, "_FLAGS_", cfg);
  606. cmValue flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
  607. fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
  608. cmOutputConverter::EscapeForCMake(*flagsCfg).c_str());
  609. }
  610. } break;
  611. }
  612. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
  613. case cmPolicies::WARN:
  614. if (this->Makefile->PolicyOptionalWarningEnabled(
  615. "CMAKE_POLICY_WARNING_CMP0056")) {
  616. std::ostringstream w;
  617. /* clang-format off */
  618. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0056) << "\n"
  619. "For compatibility with older versions of CMake, try_compile "
  620. "is not honoring caller link flags (e.g. CMAKE_EXE_LINKER_FLAGS) "
  621. "in the test project."
  622. ;
  623. /* clang-format on */
  624. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  625. }
  626. CM_FALLTHROUGH;
  627. case cmPolicies::OLD:
  628. // OLD behavior is to do nothing.
  629. break;
  630. case cmPolicies::REQUIRED_IF_USED:
  631. case cmPolicies::REQUIRED_ALWAYS:
  632. this->Makefile->IssueMessage(
  633. MessageType::FATAL_ERROR,
  634. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0056));
  635. CM_FALLTHROUGH;
  636. case cmPolicies::NEW:
  637. // NEW behavior is to pass linker flags.
  638. {
  639. cmValue exeLinkFlags =
  640. this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
  641. fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
  642. cmOutputConverter::EscapeForCMake(*exeLinkFlags).c_str());
  643. }
  644. break;
  645. }
  646. fprintf(fout,
  647. "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
  648. " ${EXE_LINKER_FLAGS}\")\n");
  649. fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
  650. fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
  651. fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
  652. // handle any compile flags we need to pass on
  653. if (!compileDefs.empty()) {
  654. // Pass using bracket arguments to preserve content.
  655. fprintf(fout, "add_definitions([==[%s]==])\n",
  656. cmJoin(compileDefs, "]==] [==[").c_str());
  657. }
  658. /* Use a random file name to avoid rapid creation and deletion
  659. of the same executable name (some filesystems fail on that). */
  660. snprintf(targetNameBuf, sizeof(targetNameBuf), "cmTC_%05x",
  661. cmSystemTools::RandomSeed() & 0xFFFFF);
  662. targetName = targetNameBuf;
  663. if (!targets.empty()) {
  664. std::string fname = "/" + std::string(targetName) + "Targets.cmake";
  665. cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile,
  666. testLangs);
  667. tcfg.SetExportFile((this->BinaryDirectory + fname).c_str());
  668. tcfg.SetConfig(tcConfig);
  669. if (!tcfg.GenerateImportFile()) {
  670. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  671. "could not write export file.");
  672. fclose(fout);
  673. return -1;
  674. }
  675. fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  676. fname.c_str());
  677. }
  678. /* Set the appropriate policy information for ENABLE_EXPORTS */
  679. fprintf(fout, "cmake_policy(SET CMP0065 %s)\n",
  680. this->Makefile->GetPolicyStatus(cmPolicies::CMP0065) ==
  681. cmPolicies::NEW
  682. ? "NEW"
  683. : "OLD");
  684. /* Set the appropriate policy information for PIE link flags */
  685. fprintf(fout, "cmake_policy(SET CMP0083 %s)\n",
  686. this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
  687. cmPolicies::NEW
  688. ? "NEW"
  689. : "OLD");
  690. // Workaround for -Wl,-headerpad_max_install_names issue until we can avoid
  691. // adding that flag in the platform and compiler language files
  692. fprintf(fout,
  693. "include(\"${CMAKE_ROOT}/Modules/Internal/"
  694. "HeaderpadWorkaround.cmake\")\n");
  695. if (targetType == cmStateEnums::EXECUTABLE) {
  696. /* Put the executable at a known location (for COPY_FILE). */
  697. fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  698. this->BinaryDirectory.c_str());
  699. /* Create the actual executable. */
  700. fprintf(fout, "add_executable(%s", targetName.c_str());
  701. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  702. {
  703. /* Put the static library at a known location (for COPY_FILE). */
  704. fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
  705. this->BinaryDirectory.c_str());
  706. /* Create the actual static library. */
  707. fprintf(fout, "add_library(%s STATIC", targetName.c_str());
  708. }
  709. for (std::string const& si : sources) {
  710. fprintf(fout, " \"%s\"", si.c_str());
  711. // Add dependencies on any non-temporary sources.
  712. if (si.find("CMakeTmp") == std::string::npos) {
  713. this->Makefile->AddCMakeDependFile(si);
  714. }
  715. }
  716. fprintf(fout, ")\n");
  717. cState.Enabled(testLangs.find("C") != testLangs.end());
  718. cxxState.Enabled(testLangs.find("CXX") != testLangs.end());
  719. cudaState.Enabled(testLangs.find("CUDA") != testLangs.end());
  720. hipState.Enabled(testLangs.find("HIP") != testLangs.end());
  721. objcState.Enabled(testLangs.find("OBJC") != testLangs.end());
  722. objcxxState.Enabled(testLangs.find("OBJCXX") != testLangs.end());
  723. bool warnCMP0067 = false;
  724. bool honorStandard = true;
  725. if (cState.DidNone() && cxxState.DidNone() && objcState.DidNone() &&
  726. objcxxState.DidNone() && cudaState.DidNone() && hipState.DidNone()) {
  727. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0067)) {
  728. case cmPolicies::WARN:
  729. warnCMP0067 = this->Makefile->PolicyOptionalWarningEnabled(
  730. "CMAKE_POLICY_WARNING_CMP0067");
  731. CM_FALLTHROUGH;
  732. case cmPolicies::OLD:
  733. // OLD behavior is to not honor the language standard variables.
  734. honorStandard = false;
  735. break;
  736. case cmPolicies::REQUIRED_IF_USED:
  737. case cmPolicies::REQUIRED_ALWAYS:
  738. this->Makefile->IssueMessage(
  739. MessageType::FATAL_ERROR,
  740. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0067));
  741. break;
  742. case cmPolicies::NEW:
  743. // NEW behavior is to honor the language standard variables.
  744. // We already initialized honorStandard to true.
  745. break;
  746. }
  747. }
  748. std::vector<std::string> warnCMP0067Variables;
  749. cState.LoadUnsetPropertyValues(this->Makefile, honorStandard, warnCMP0067,
  750. warnCMP0067Variables);
  751. cxxState.LoadUnsetPropertyValues(this->Makefile, honorStandard,
  752. warnCMP0067, warnCMP0067Variables);
  753. cudaState.LoadUnsetPropertyValues(this->Makefile, honorStandard,
  754. warnCMP0067, warnCMP0067Variables);
  755. hipState.LoadUnsetPropertyValues(this->Makefile, honorStandard,
  756. warnCMP0067, warnCMP0067Variables);
  757. objcState.LoadUnsetPropertyValues(this->Makefile, honorStandard,
  758. warnCMP0067, warnCMP0067Variables);
  759. objcxxState.LoadUnsetPropertyValues(this->Makefile, honorStandard,
  760. warnCMP0067, warnCMP0067Variables);
  761. if (!warnCMP0067Variables.empty()) {
  762. std::ostringstream w;
  763. /* clang-format off */
  764. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0067) << "\n"
  765. "For compatibility with older versions of CMake, try_compile "
  766. "is not honoring language standard variables in the test project:\n"
  767. ;
  768. /* clang-format on */
  769. for (std::string const& vi : warnCMP0067Variables) {
  770. w << " " << vi << "\n";
  771. }
  772. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  773. }
  774. cState.WriteProperties(fout, targetName);
  775. cxxState.WriteProperties(fout, targetName);
  776. cudaState.WriteProperties(fout, targetName);
  777. hipState.WriteProperties(fout, targetName);
  778. objcState.WriteProperties(fout, targetName);
  779. objcxxState.WriteProperties(fout, targetName);
  780. if (!linkOptions.empty()) {
  781. std::vector<std::string> options;
  782. options.reserve(linkOptions.size());
  783. for (const auto& option : linkOptions) {
  784. options.emplace_back(cmOutputConverter::EscapeForCMake(option));
  785. }
  786. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  787. fprintf(fout,
  788. "set_property(TARGET %s PROPERTY STATIC_LIBRARY_OPTIONS %s)\n",
  789. targetName.c_str(), cmJoin(options, " ").c_str());
  790. } else {
  791. fprintf(fout, "target_link_options(%s PRIVATE %s)\n",
  792. targetName.c_str(), cmJoin(options, " ").c_str());
  793. }
  794. }
  795. if (useOldLinkLibs) {
  796. fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
  797. targetName.c_str());
  798. } else {
  799. fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
  800. libsToLink.c_str());
  801. }
  802. fclose(fout);
  803. projectName = "CMAKE_TRY_COMPILE";
  804. }
  805. // Forward a set of variables to the inner project cache.
  806. if ((this->SrcFileSignature ||
  807. this->Makefile->GetPolicyStatus(cmPolicies::CMP0137) ==
  808. cmPolicies::NEW) &&
  809. !this->Makefile->IsOn("CMAKE_TRY_COMPILE_NO_PLATFORM_VARIABLES")) {
  810. std::set<std::string> vars;
  811. vars.insert(&c_properties[lang_property_start],
  812. &c_properties[lang_property_start + lang_property_size]);
  813. vars.insert(&cxx_properties[lang_property_start],
  814. &cxx_properties[lang_property_start + lang_property_size]);
  815. vars.insert(&cuda_properties[lang_property_start],
  816. &cuda_properties[lang_property_start + lang_property_size]);
  817. vars.insert(&fortran_properties[lang_property_start],
  818. &fortran_properties[lang_property_start + lang_property_size]);
  819. vars.insert(&hip_properties[lang_property_start],
  820. &hip_properties[lang_property_start + lang_property_size]);
  821. vars.insert(&objc_properties[lang_property_start],
  822. &objc_properties[lang_property_start + lang_property_size]);
  823. vars.insert(&objcxx_properties[lang_property_start],
  824. &objcxx_properties[lang_property_start + lang_property_size]);
  825. vars.insert(&ispc_properties[lang_property_start],
  826. &ispc_properties[lang_property_start + lang_property_size]);
  827. vars.insert(&swift_properties[lang_property_start],
  828. &swift_properties[lang_property_start + lang_property_size]);
  829. vars.insert(kCMAKE_CUDA_ARCHITECTURES);
  830. vars.insert(kCMAKE_CUDA_RUNTIME_LIBRARY);
  831. vars.insert(kCMAKE_ENABLE_EXPORTS);
  832. vars.insert(kCMAKE_HIP_ARCHITECTURES);
  833. vars.insert(kCMAKE_HIP_RUNTIME_LIBRARY);
  834. vars.insert(kCMAKE_ISPC_INSTRUCTION_SETS);
  835. vars.insert(kCMAKE_ISPC_HEADER_SUFFIX);
  836. vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
  837. vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
  838. vars.insert(kCMAKE_OSX_ARCHITECTURES);
  839. vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
  840. vars.insert(kCMAKE_OSX_SYSROOT);
  841. vars.insert(kCMAKE_APPLE_ARCH_SYSROOTS);
  842. vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
  843. vars.insert(kCMAKE_SYSROOT);
  844. vars.insert(kCMAKE_SYSROOT_COMPILE);
  845. vars.insert(kCMAKE_SYSROOT_LINK);
  846. vars.insert(kCMAKE_WARN_DEPRECATED);
  847. vars.emplace("CMAKE_MSVC_RUNTIME_LIBRARY"_s);
  848. vars.emplace("CMAKE_WATCOM_RUNTIME_LIBRARY"_s);
  849. if (cmValue varListStr = this->Makefile->GetDefinition(
  850. kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
  851. std::vector<std::string> varList = cmExpandedList(*varListStr);
  852. vars.insert(varList.begin(), varList.end());
  853. }
  854. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
  855. cmPolicies::NEW) {
  856. // To ensure full support of PIE, propagate cache variables
  857. // driving the link options
  858. vars.insert(&c_properties[pie_property_start],
  859. &c_properties[pie_property_start + pie_property_size]);
  860. vars.insert(&cxx_properties[pie_property_start],
  861. &cxx_properties[pie_property_start + pie_property_size]);
  862. vars.insert(&cuda_properties[pie_property_start],
  863. &cuda_properties[pie_property_start + pie_property_size]);
  864. vars.insert(&fortran_properties[pie_property_start],
  865. &fortran_properties[pie_property_start + pie_property_size]);
  866. vars.insert(&hip_properties[pie_property_start],
  867. &hip_properties[pie_property_start + pie_property_size]);
  868. vars.insert(&objc_properties[pie_property_start],
  869. &objc_properties[pie_property_start + pie_property_size]);
  870. vars.insert(&objcxx_properties[pie_property_start],
  871. &objcxx_properties[pie_property_start + pie_property_size]);
  872. vars.insert(&ispc_properties[pie_property_start],
  873. &ispc_properties[pie_property_start + pie_property_size]);
  874. vars.insert(&swift_properties[pie_property_start],
  875. &swift_properties[pie_property_start + pie_property_size]);
  876. }
  877. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  878. So the user can set CMAKE_OSX_ARCHITECTURES to i386;ppc and then set
  879. CMAKE_TRY_COMPILE_OSX_ARCHITECTURES first to i386 and then to ppc to
  880. have the tests run for each specific architecture. Since
  881. cmLocalGenerator doesn't allow building for "the other"
  882. architecture only via CMAKE_OSX_ARCHITECTURES.
  883. */
  884. if (cmValue tcArchs = this->Makefile->GetDefinition(
  885. kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES)) {
  886. vars.erase(kCMAKE_OSX_ARCHITECTURES);
  887. std::string flag = "-DCMAKE_OSX_ARCHITECTURES=" + *tcArchs;
  888. cmakeFlags.emplace_back(std::move(flag));
  889. }
  890. for (std::string const& var : vars) {
  891. if (cmValue val = this->Makefile->GetDefinition(var)) {
  892. std::string flag = "-D" + var + "=" + *val;
  893. cmakeFlags.emplace_back(std::move(flag));
  894. }
  895. }
  896. }
  897. if (this->Makefile->GetState()->UseGhsMultiIDE()) {
  898. // Forward the GHS variables to the inner project cache.
  899. for (std::string const& var : ghs_platform_vars) {
  900. if (cmValue val = this->Makefile->GetDefinition(var)) {
  901. std::string flag = "-D" + var + "=" + "'" + *val + "'";
  902. cmakeFlags.emplace_back(std::move(flag));
  903. }
  904. }
  905. }
  906. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  907. cmSystemTools::ResetErrorOccuredFlag();
  908. std::string output;
  909. // actually do the try compile now that everything is setup
  910. int res = this->Makefile->TryCompile(
  911. sourceDirectory, this->BinaryDirectory, projectName, targetName,
  912. this->SrcFileSignature, cmake::NO_BUILD_PARALLEL_LEVEL, &cmakeFlags,
  913. output);
  914. if (erroroc) {
  915. cmSystemTools::SetErrorOccured();
  916. }
  917. // set the result var to the return value to indicate success or failure
  918. this->Makefile->AddCacheDefinition(argv[0], (res == 0 ? "TRUE" : "FALSE"),
  919. "Result of TRY_COMPILE",
  920. cmStateEnums::INTERNAL);
  921. if (!outputVariable.empty()) {
  922. this->Makefile->AddDefinition(outputVariable, output);
  923. }
  924. if (this->SrcFileSignature) {
  925. std::string copyFileErrorMessage;
  926. this->FindOutputFile(targetName, targetType);
  927. if ((res == 0) && !copyFile.empty()) {
  928. if (this->OutputFile.empty() ||
  929. !cmSystemTools::CopyFileAlways(this->OutputFile, copyFile)) {
  930. std::ostringstream emsg;
  931. /* clang-format off */
  932. emsg << "Cannot copy output executable\n"
  933. << " '" << this->OutputFile << "'\n"
  934. << "to destination specified by COPY_FILE:\n"
  935. << " '" << copyFile << "'\n";
  936. /* clang-format on */
  937. if (!this->FindErrorMessage.empty()) {
  938. emsg << this->FindErrorMessage;
  939. }
  940. if (copyFileError.empty()) {
  941. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, emsg.str());
  942. return -1;
  943. }
  944. copyFileErrorMessage = emsg.str();
  945. }
  946. }
  947. if (!copyFileError.empty()) {
  948. this->Makefile->AddDefinition(copyFileError, copyFileErrorMessage);
  949. }
  950. }
  951. return res;
  952. }
  953. void cmCoreTryCompile::CleanupFiles(std::string const& binDir)
  954. {
  955. if (binDir.empty()) {
  956. return;
  957. }
  958. if (binDir.find("CMakeTmp") == std::string::npos) {
  959. cmSystemTools::Error(
  960. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  961. "CMakeTmp:" +
  962. binDir);
  963. return;
  964. }
  965. cmsys::Directory dir;
  966. dir.Load(binDir);
  967. std::set<std::string> deletedFiles;
  968. for (unsigned long i = 0; i < dir.GetNumberOfFiles(); ++i) {
  969. const char* fileName = dir.GetFile(i);
  970. if (strcmp(fileName, ".") != 0 && strcmp(fileName, "..") != 0 &&
  971. // Do not delete NFS temporary files.
  972. !cmHasPrefix(fileName, ".nfs")) {
  973. if (deletedFiles.insert(fileName).second) {
  974. std::string const fullPath =
  975. std::string(binDir).append("/").append(fileName);
  976. if (cmSystemTools::FileIsSymlink(fullPath)) {
  977. cmSystemTools::RemoveFile(fullPath);
  978. } else if (cmSystemTools::FileIsDirectory(fullPath)) {
  979. this->CleanupFiles(fullPath);
  980. cmSystemTools::RemoveADirectory(fullPath);
  981. } else {
  982. #ifdef _WIN32
  983. // Sometimes anti-virus software hangs on to new files so we
  984. // cannot delete them immediately. Try a few times.
  985. cmSystemTools::WindowsFileRetry retry =
  986. cmSystemTools::GetWindowsFileRetry();
  987. cmsys::Status status;
  988. while (!((status = cmSystemTools::RemoveFile(fullPath))) &&
  989. --retry.Count && cmSystemTools::FileExists(fullPath)) {
  990. cmSystemTools::Delay(retry.Delay);
  991. }
  992. if (retry.Count == 0)
  993. #else
  994. cmsys::Status status = cmSystemTools::RemoveFile(fullPath);
  995. if (!status)
  996. #endif
  997. {
  998. this->Makefile->IssueMessage(
  999. MessageType::FATAL_ERROR,
  1000. cmStrCat("The file:\n ", fullPath,
  1001. "\ncould not be removed:\n ", status.GetString()));
  1002. }
  1003. }
  1004. }
  1005. }
  1006. }
  1007. }
  1008. void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
  1009. cmStateEnums::TargetType targetType)
  1010. {
  1011. this->FindErrorMessage.clear();
  1012. this->OutputFile.clear();
  1013. std::string tmpOutputFile = "/";
  1014. if (targetType == cmStateEnums::EXECUTABLE) {
  1015. tmpOutputFile += targetName;
  1016. tmpOutputFile +=
  1017. this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  1018. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  1019. {
  1020. tmpOutputFile +=
  1021. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX");
  1022. tmpOutputFile += targetName;
  1023. tmpOutputFile +=
  1024. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX");
  1025. }
  1026. // a list of directories where to search for the compilation result
  1027. // at first directly in the binary dir
  1028. std::vector<std::string> searchDirs;
  1029. searchDirs.emplace_back();
  1030. cmValue config =
  1031. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  1032. // if a config was specified try that first
  1033. if (cmNonempty(config)) {
  1034. std::string tmp = cmStrCat('/', *config);
  1035. searchDirs.emplace_back(std::move(tmp));
  1036. }
  1037. searchDirs.emplace_back("/Debug");
  1038. #if defined(__APPLE__)
  1039. std::string app = "/" + targetName + ".app";
  1040. if (cmNonempty(config)) {
  1041. std::string tmp = cmStrCat('/', *config, app);
  1042. searchDirs.emplace_back(std::move(tmp));
  1043. }
  1044. std::string tmp = "/Debug" + app;
  1045. searchDirs.emplace_back(std::move(tmp));
  1046. searchDirs.emplace_back(std::move(app));
  1047. #endif
  1048. searchDirs.emplace_back("/Development");
  1049. for (std::string const& sdir : searchDirs) {
  1050. std::string command = cmStrCat(this->BinaryDirectory, sdir, tmpOutputFile);
  1051. if (cmSystemTools::FileExists(command)) {
  1052. this->OutputFile = cmSystemTools::CollapseFullPath(command);
  1053. return;
  1054. }
  1055. }
  1056. std::ostringstream emsg;
  1057. emsg << "Unable to find the executable at any of:\n";
  1058. emsg << cmWrap(" " + this->BinaryDirectory, searchDirs, tmpOutputFile, "\n")
  1059. << "\n";
  1060. this->FindErrorMessage = emsg.str();
  1061. }