cmCoreTryCompile.cxx 42 KB

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