1
0

cmCoreTryCompile.cxx 39 KB

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