cmCoreTryCompile.cxx 40 KB

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