cmCoreTryCompile.cxx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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 <cmConfigure.h>
  5. #include <cmsys/Directory.hxx>
  6. #include <set>
  7. #include <sstream>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include "cmAlgorithms.h"
  11. #include "cmExportTryCompileFileGenerator.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmOutputConverter.h"
  15. #include "cmPolicies.h"
  16. #include "cmState.h"
  17. #include "cmSystemTools.h"
  18. #include "cmTarget.h"
  19. #include "cmVersion.h"
  20. #include "cmake.h"
  21. static std::string const kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN =
  22. "CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN";
  23. static std::string const kCMAKE_C_COMPILER_TARGET = "CMAKE_C_COMPILER_TARGET";
  24. static std::string const kCMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN =
  25. "CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN";
  26. static std::string const kCMAKE_CXX_COMPILER_TARGET =
  27. "CMAKE_CXX_COMPILER_TARGET";
  28. static std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
  29. static std::string const kCMAKE_LINK_SEARCH_END_STATIC =
  30. "CMAKE_LINK_SEARCH_END_STATIC";
  31. static std::string const kCMAKE_LINK_SEARCH_START_STATIC =
  32. "CMAKE_LINK_SEARCH_START_STATIC";
  33. static std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
  34. static std::string const kCMAKE_OSX_DEPLOYMENT_TARGET =
  35. "CMAKE_OSX_DEPLOYMENT_TARGET";
  36. static std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
  37. static std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
  38. "CMAKE_POSITION_INDEPENDENT_CODE";
  39. static std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
  40. static std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
  41. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
  42. static std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
  43. "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
  44. int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
  45. bool isTryRun)
  46. {
  47. this->BinaryDirectory = argv[1];
  48. this->OutputFile = "";
  49. // which signature were we called with ?
  50. this->SrcFileSignature = true;
  51. cmStateEnums::TargetType targetType = cmStateEnums::EXECUTABLE;
  52. const char* tt =
  53. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_TARGET_TYPE");
  54. if (!isTryRun && tt && *tt) {
  55. if (strcmp(tt, cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE)) ==
  56. 0) {
  57. targetType = cmStateEnums::EXECUTABLE;
  58. } else if (strcmp(tt, cmState::GetTargetTypeName(
  59. cmStateEnums::STATIC_LIBRARY)) == 0) {
  60. targetType = cmStateEnums::STATIC_LIBRARY;
  61. } else {
  62. this->Makefile->IssueMessage(
  63. cmake::FATAL_ERROR, std::string("Invalid value '") + tt +
  64. "' for "
  65. "CMAKE_TRY_COMPILE_TARGET_TYPE. Only "
  66. "'" +
  67. cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE) + "' and "
  68. "'" +
  69. cmState::GetTargetTypeName(cmStateEnums::STATIC_LIBRARY) +
  70. "' "
  71. "are allowed.");
  72. return -1;
  73. }
  74. }
  75. const char* sourceDirectory = argv[2].c_str();
  76. const char* projectName = CM_NULLPTR;
  77. std::string targetName;
  78. std::vector<std::string> cmakeFlags(1, "CMAKE_FLAGS"); // fake argv[0]
  79. std::vector<std::string> compileDefs;
  80. std::string outputVariable;
  81. std::string copyFile;
  82. std::string copyFileError;
  83. std::vector<std::string> targets;
  84. std::string libsToLink = " ";
  85. bool useOldLinkLibs = true;
  86. char targetNameBuf[64];
  87. bool didOutputVariable = false;
  88. bool didCopyFile = false;
  89. bool didCopyFileError = false;
  90. bool useSources = argv[2] == "SOURCES";
  91. std::vector<std::string> sources;
  92. enum Doing
  93. {
  94. DoingNone,
  95. DoingCMakeFlags,
  96. DoingCompileDefinitions,
  97. DoingLinkLibraries,
  98. DoingOutputVariable,
  99. DoingCopyFile,
  100. DoingCopyFileError,
  101. DoingSources
  102. };
  103. Doing doing = useSources ? DoingSources : DoingNone;
  104. for (size_t i = 3; i < argv.size(); ++i) {
  105. if (argv[i] == "CMAKE_FLAGS") {
  106. doing = DoingCMakeFlags;
  107. } else if (argv[i] == "COMPILE_DEFINITIONS") {
  108. doing = DoingCompileDefinitions;
  109. } else if (argv[i] == "LINK_LIBRARIES") {
  110. doing = DoingLinkLibraries;
  111. useOldLinkLibs = false;
  112. } else if (argv[i] == "OUTPUT_VARIABLE") {
  113. doing = DoingOutputVariable;
  114. didOutputVariable = true;
  115. } else if (argv[i] == "COPY_FILE") {
  116. doing = DoingCopyFile;
  117. didCopyFile = true;
  118. } else if (argv[i] == "COPY_FILE_ERROR") {
  119. doing = DoingCopyFileError;
  120. didCopyFileError = true;
  121. } else if (doing == DoingCMakeFlags) {
  122. cmakeFlags.push_back(argv[i]);
  123. } else if (doing == DoingCompileDefinitions) {
  124. compileDefs.push_back(argv[i]);
  125. } else if (doing == DoingLinkLibraries) {
  126. libsToLink += "\"" + cmSystemTools::TrimWhitespace(argv[i]) + "\" ";
  127. if (cmTarget* tgt = this->Makefile->FindTargetToUse(argv[i])) {
  128. switch (tgt->GetType()) {
  129. case cmStateEnums::SHARED_LIBRARY:
  130. case cmStateEnums::STATIC_LIBRARY:
  131. case cmStateEnums::INTERFACE_LIBRARY:
  132. case cmStateEnums::UNKNOWN_LIBRARY:
  133. break;
  134. case cmStateEnums::EXECUTABLE:
  135. if (tgt->IsExecutableWithExports()) {
  136. break;
  137. }
  138. default:
  139. this->Makefile->IssueMessage(
  140. cmake::FATAL_ERROR,
  141. "Only libraries may be used as try_compile or try_run IMPORTED "
  142. "LINK_LIBRARIES. Got " +
  143. std::string(tgt->GetName()) + " of "
  144. "type " +
  145. cmState::GetTargetTypeName(tgt->GetType()) + ".");
  146. return -1;
  147. }
  148. if (tgt->IsImported()) {
  149. targets.push_back(argv[i]);
  150. }
  151. }
  152. } else if (doing == DoingOutputVariable) {
  153. outputVariable = argv[i];
  154. doing = DoingNone;
  155. } else if (doing == DoingCopyFile) {
  156. copyFile = argv[i];
  157. doing = DoingNone;
  158. } else if (doing == DoingCopyFileError) {
  159. copyFileError = argv[i];
  160. doing = DoingNone;
  161. } else if (doing == DoingSources) {
  162. sources.push_back(argv[i]);
  163. } else if (i == 3) {
  164. this->SrcFileSignature = false;
  165. projectName = argv[i].c_str();
  166. } else if (i == 4 && !this->SrcFileSignature) {
  167. targetName = argv[i];
  168. } else {
  169. std::ostringstream m;
  170. m << "try_compile given unknown argument \"" << argv[i] << "\".";
  171. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, m.str());
  172. }
  173. }
  174. if (didCopyFile && copyFile.empty()) {
  175. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  176. "COPY_FILE must be followed by a file path");
  177. return -1;
  178. }
  179. if (didCopyFileError && copyFileError.empty()) {
  180. this->Makefile->IssueMessage(
  181. cmake::FATAL_ERROR,
  182. "COPY_FILE_ERROR must be followed by a variable name");
  183. return -1;
  184. }
  185. if (didCopyFileError && !didCopyFile) {
  186. this->Makefile->IssueMessage(
  187. cmake::FATAL_ERROR, "COPY_FILE_ERROR may be used only with COPY_FILE");
  188. return -1;
  189. }
  190. if (didOutputVariable && outputVariable.empty()) {
  191. this->Makefile->IssueMessage(
  192. cmake::FATAL_ERROR,
  193. "OUTPUT_VARIABLE must be followed by a variable name");
  194. return -1;
  195. }
  196. if (useSources && sources.empty()) {
  197. this->Makefile->IssueMessage(
  198. cmake::FATAL_ERROR,
  199. "SOURCES must be followed by at least one source file");
  200. return -1;
  201. }
  202. // compute the binary dir when TRY_COMPILE is called with a src file
  203. // signature
  204. if (this->SrcFileSignature) {
  205. this->BinaryDirectory += cmake::GetCMakeFilesDirectory();
  206. this->BinaryDirectory += "/CMakeTmp";
  207. } else {
  208. // only valid for srcfile signatures
  209. if (!compileDefs.empty()) {
  210. this->Makefile->IssueMessage(
  211. cmake::FATAL_ERROR,
  212. "COMPILE_DEFINITIONS specified on a srcdir type TRY_COMPILE");
  213. return -1;
  214. }
  215. if (!copyFile.empty()) {
  216. this->Makefile->IssueMessage(
  217. cmake::FATAL_ERROR,
  218. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  219. return -1;
  220. }
  221. }
  222. // make sure the binary directory exists
  223. cmSystemTools::MakeDirectory(this->BinaryDirectory.c_str());
  224. // do not allow recursive try Compiles
  225. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
  226. std::ostringstream e;
  227. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  228. << " " << this->BinaryDirectory << "\n";
  229. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  230. return -1;
  231. }
  232. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  233. // which signature are we using? If we are using var srcfile bindir
  234. if (this->SrcFileSignature) {
  235. // remove any CMakeCache.txt files so we will have a clean test
  236. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  237. cmSystemTools::RemoveFile(ccFile);
  238. // Choose sources.
  239. if (!useSources) {
  240. sources.push_back(argv[2]);
  241. }
  242. // Detect languages to enable.
  243. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  244. std::set<std::string> testLangs;
  245. for (std::vector<std::string>::iterator si = sources.begin();
  246. si != sources.end(); ++si) {
  247. std::string ext = cmSystemTools::GetFilenameLastExtension(*si);
  248. std::string lang = gg->GetLanguageFromExtension(ext.c_str());
  249. if (!lang.empty()) {
  250. testLangs.insert(lang);
  251. } else {
  252. std::ostringstream err;
  253. err << "Unknown extension \"" << ext << "\" for file\n"
  254. << " " << *si << "\n"
  255. << "try_compile() works only for enabled languages. "
  256. << "Currently these are:\n ";
  257. std::vector<std::string> langs;
  258. gg->GetEnabledLanguages(langs);
  259. err << cmJoin(langs, " ");
  260. err << "\nSee project() command to enable other languages.";
  261. this->Makefile->IssueMessage(cmake::FATAL_ERROR, err.str());
  262. return -1;
  263. }
  264. }
  265. std::string const tcConfig =
  266. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  267. // we need to create a directory and CMakeLists file etc...
  268. // first create the directories
  269. sourceDirectory = this->BinaryDirectory.c_str();
  270. // now create a CMakeLists.txt file in that directory
  271. FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
  272. if (!fout) {
  273. std::ostringstream e;
  274. /* clang-format off */
  275. e << "Failed to open\n"
  276. << " " << outFileName << "\n"
  277. << cmSystemTools::GetLastSystemError();
  278. /* clang-format on */
  279. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  280. return -1;
  281. }
  282. const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  283. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  284. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  285. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  286. if (def) {
  287. fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def);
  288. }
  289. std::string projectLangs;
  290. for (std::set<std::string>::iterator li = testLangs.begin();
  291. li != testLangs.end(); ++li) {
  292. projectLangs += " " + *li;
  293. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  294. std::string rulesOverrideLang = rulesOverrideBase + "_" + *li;
  295. if (const char* rulesOverridePath =
  296. this->Makefile->GetDefinition(rulesOverrideLang)) {
  297. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
  298. rulesOverridePath);
  299. } else if (const char* rulesOverridePath2 =
  300. this->Makefile->GetDefinition(rulesOverrideBase)) {
  301. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
  302. rulesOverridePath2);
  303. }
  304. }
  305. fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  306. fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
  307. for (std::set<std::string>::iterator li = testLangs.begin();
  308. li != testLangs.end(); ++li) {
  309. std::string langFlags = "CMAKE_" + *li + "_FLAGS";
  310. const char* flags = this->Makefile->GetDefinition(langFlags);
  311. fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li->c_str(),
  312. cmOutputConverter::EscapeForCMake(flags ? flags : "").c_str());
  313. fprintf(fout, "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
  314. " ${COMPILE_DEFINITIONS}\")\n",
  315. li->c_str(), li->c_str());
  316. }
  317. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
  318. case cmPolicies::WARN:
  319. if (this->Makefile->PolicyOptionalWarningEnabled(
  320. "CMAKE_POLICY_WARNING_CMP0066")) {
  321. std::ostringstream w;
  322. /* clang-format off */
  323. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
  324. "For compatibility with older versions of CMake, try_compile "
  325. "is not honoring caller config-specific compiler flags "
  326. "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
  327. ;
  328. /* clang-format on */
  329. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  330. }
  331. case cmPolicies::OLD:
  332. // OLD behavior is to do nothing.
  333. break;
  334. case cmPolicies::REQUIRED_IF_USED:
  335. case cmPolicies::REQUIRED_ALWAYS:
  336. this->Makefile->IssueMessage(
  337. cmake::FATAL_ERROR,
  338. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0066));
  339. case cmPolicies::NEW: {
  340. // NEW behavior is to pass config-specific compiler flags.
  341. static std::string const cfgDefault = "DEBUG";
  342. std::string const cfg =
  343. !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
  344. for (std::set<std::string>::iterator li = testLangs.begin();
  345. li != testLangs.end(); ++li) {
  346. std::string const langFlagsCfg = "CMAKE_" + *li + "_FLAGS_" + cfg;
  347. const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
  348. fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
  349. cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "")
  350. .c_str());
  351. }
  352. } break;
  353. }
  354. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
  355. case cmPolicies::WARN:
  356. if (this->Makefile->PolicyOptionalWarningEnabled(
  357. "CMAKE_POLICY_WARNING_CMP0056")) {
  358. std::ostringstream w;
  359. /* clang-format off */
  360. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0056) << "\n"
  361. "For compatibility with older versions of CMake, try_compile "
  362. "is not honoring caller link flags (e.g. CMAKE_EXE_LINKER_FLAGS) "
  363. "in the test project."
  364. ;
  365. /* clang-format on */
  366. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  367. }
  368. case cmPolicies::OLD:
  369. // OLD behavior is to do nothing.
  370. break;
  371. case cmPolicies::REQUIRED_IF_USED:
  372. case cmPolicies::REQUIRED_ALWAYS:
  373. this->Makefile->IssueMessage(
  374. cmake::FATAL_ERROR,
  375. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0056));
  376. case cmPolicies::NEW:
  377. // NEW behavior is to pass linker flags.
  378. {
  379. const char* exeLinkFlags =
  380. this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
  381. fprintf(
  382. fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
  383. cmOutputConverter::EscapeForCMake(exeLinkFlags ? exeLinkFlags : "")
  384. .c_str());
  385. }
  386. break;
  387. }
  388. fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
  389. " ${EXE_LINKER_FLAGS}\")\n");
  390. fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
  391. fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
  392. fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
  393. // handle any compile flags we need to pass on
  394. if (!compileDefs.empty()) {
  395. fprintf(fout, "add_definitions(%s)\n", cmJoin(compileDefs, " ").c_str());
  396. }
  397. /* Use a random file name to avoid rapid creation and deletion
  398. of the same executable name (some filesystems fail on that). */
  399. sprintf(targetNameBuf, "cmTC_%05x", cmSystemTools::RandomSeed() & 0xFFFFF);
  400. targetName = targetNameBuf;
  401. if (!targets.empty()) {
  402. std::string fname = "/" + std::string(targetName) + "Targets.cmake";
  403. cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile);
  404. tcfg.SetExportFile((this->BinaryDirectory + fname).c_str());
  405. tcfg.SetConfig(tcConfig);
  406. if (!tcfg.GenerateImportFile()) {
  407. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  408. "could not write export file.");
  409. fclose(fout);
  410. return -1;
  411. }
  412. fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  413. fname.c_str());
  414. }
  415. // Forward a set of variables to the inner project cache.
  416. {
  417. std::set<std::string> vars;
  418. vars.insert(kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN);
  419. vars.insert(kCMAKE_C_COMPILER_TARGET);
  420. vars.insert(kCMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN);
  421. vars.insert(kCMAKE_CXX_COMPILER_TARGET);
  422. vars.insert(kCMAKE_ENABLE_EXPORTS);
  423. vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
  424. vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
  425. vars.insert(kCMAKE_OSX_ARCHITECTURES);
  426. vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
  427. vars.insert(kCMAKE_OSX_SYSROOT);
  428. vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
  429. vars.insert(kCMAKE_SYSROOT);
  430. if (const char* varListStr = this->Makefile->GetDefinition(
  431. kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
  432. std::vector<std::string> varList;
  433. cmSystemTools::ExpandListArgument(varListStr, varList);
  434. vars.insert(varList.begin(), varList.end());
  435. }
  436. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  437. So the user can set CMAKE_OSX_ARCHITECTURES to i386;ppc and then set
  438. CMAKE_TRY_COMPILE_OSX_ARCHITECTURES first to i386 and then to ppc to
  439. have the tests run for each specific architecture. Since
  440. cmLocalGenerator doesn't allow building for "the other"
  441. architecture only via CMAKE_OSX_ARCHITECTURES.
  442. */
  443. if (const char* tcArchs = this->Makefile->GetDefinition(
  444. kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES)) {
  445. vars.erase(kCMAKE_OSX_ARCHITECTURES);
  446. std::string flag = "-DCMAKE_OSX_ARCHITECTURES=" + std::string(tcArchs);
  447. cmakeFlags.push_back(flag);
  448. }
  449. for (std::set<std::string>::iterator vi = vars.begin(); vi != vars.end();
  450. ++vi) {
  451. std::string const& var = *vi;
  452. if (const char* val = this->Makefile->GetDefinition(var)) {
  453. std::string flag = "-D" + var + "=" + val;
  454. cmakeFlags.push_back(flag);
  455. }
  456. }
  457. }
  458. /* Set the appropriate policy information for ENABLE_EXPORTS */
  459. fprintf(fout, "cmake_policy(SET CMP0065 %s)\n",
  460. this->Makefile->GetPolicyStatus(cmPolicies::CMP0065) ==
  461. cmPolicies::NEW
  462. ? "NEW"
  463. : "OLD");
  464. if (targetType == cmStateEnums::EXECUTABLE) {
  465. /* Put the executable at a known location (for COPY_FILE). */
  466. fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  467. this->BinaryDirectory.c_str());
  468. /* Create the actual executable. */
  469. fprintf(fout, "add_executable(%s", targetName.c_str());
  470. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  471. {
  472. /* Put the static library at a known location (for COPY_FILE). */
  473. fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
  474. this->BinaryDirectory.c_str());
  475. /* Create the actual static library. */
  476. fprintf(fout, "add_library(%s STATIC", targetName.c_str());
  477. }
  478. for (std::vector<std::string>::iterator si = sources.begin();
  479. si != sources.end(); ++si) {
  480. fprintf(fout, " \"%s\"", si->c_str());
  481. // Add dependencies on any non-temporary sources.
  482. if (si->find("CMakeTmp") == si->npos) {
  483. this->Makefile->AddCMakeDependFile(*si);
  484. }
  485. }
  486. fprintf(fout, ")\n");
  487. if (useOldLinkLibs) {
  488. fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
  489. targetName.c_str());
  490. } else {
  491. fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
  492. libsToLink.c_str());
  493. }
  494. fclose(fout);
  495. projectName = "CMAKE_TRY_COMPILE";
  496. }
  497. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  498. cmSystemTools::ResetErrorOccuredFlag();
  499. std::string output;
  500. // actually do the try compile now that everything is setup
  501. int res = this->Makefile->TryCompile(
  502. sourceDirectory, this->BinaryDirectory, projectName, targetName,
  503. this->SrcFileSignature, &cmakeFlags, output);
  504. if (erroroc) {
  505. cmSystemTools::SetErrorOccured();
  506. }
  507. // set the result var to the return value to indicate success or failure
  508. this->Makefile->AddCacheDefinition(argv[0], (res == 0 ? "TRUE" : "FALSE"),
  509. "Result of TRY_COMPILE",
  510. cmStateEnums::INTERNAL);
  511. if (!outputVariable.empty()) {
  512. this->Makefile->AddDefinition(outputVariable, output.c_str());
  513. }
  514. if (this->SrcFileSignature) {
  515. std::string copyFileErrorMessage;
  516. this->FindOutputFile(targetName, targetType);
  517. if ((res == 0) && !copyFile.empty()) {
  518. if (this->OutputFile.empty() ||
  519. !cmSystemTools::CopyFileAlways(this->OutputFile, copyFile)) {
  520. std::ostringstream emsg;
  521. /* clang-format off */
  522. emsg << "Cannot copy output executable\n"
  523. << " '" << this->OutputFile << "'\n"
  524. << "to destination specified by COPY_FILE:\n"
  525. << " '" << copyFile << "'\n";
  526. /* clang-format on */
  527. if (!this->FindErrorMessage.empty()) {
  528. emsg << this->FindErrorMessage.c_str();
  529. }
  530. if (copyFileError.empty()) {
  531. this->Makefile->IssueMessage(cmake::FATAL_ERROR, emsg.str());
  532. return -1;
  533. }
  534. copyFileErrorMessage = emsg.str();
  535. }
  536. }
  537. if (!copyFileError.empty()) {
  538. this->Makefile->AddDefinition(copyFileError,
  539. copyFileErrorMessage.c_str());
  540. }
  541. }
  542. return res;
  543. }
  544. void cmCoreTryCompile::CleanupFiles(const char* binDir)
  545. {
  546. if (!binDir) {
  547. return;
  548. }
  549. std::string bdir = binDir;
  550. if (bdir.find("CMakeTmp") == std::string::npos) {
  551. cmSystemTools::Error(
  552. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  553. "CMakeTmp:",
  554. binDir);
  555. return;
  556. }
  557. cmsys::Directory dir;
  558. dir.Load(binDir);
  559. size_t fileNum;
  560. std::set<std::string> deletedFiles;
  561. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
  562. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
  563. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
  564. if (deletedFiles.find(dir.GetFile(
  565. static_cast<unsigned long>(fileNum))) == deletedFiles.end()) {
  566. deletedFiles.insert(dir.GetFile(static_cast<unsigned long>(fileNum)));
  567. std::string fullPath = binDir;
  568. fullPath += "/";
  569. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  570. if (cmSystemTools::FileIsDirectory(fullPath)) {
  571. this->CleanupFiles(fullPath.c_str());
  572. cmSystemTools::RemoveADirectory(fullPath);
  573. } else {
  574. #ifdef _WIN32
  575. // Sometimes anti-virus software hangs on to new files so we
  576. // cannot delete them immediately. Try a few times.
  577. cmSystemTools::WindowsFileRetry retry =
  578. cmSystemTools::GetWindowsFileRetry();
  579. while (!cmSystemTools::RemoveFile(fullPath.c_str()) &&
  580. --retry.Count &&
  581. cmSystemTools::FileExists(fullPath.c_str())) {
  582. cmSystemTools::Delay(retry.Delay);
  583. }
  584. if (retry.Count == 0)
  585. #else
  586. if (!cmSystemTools::RemoveFile(fullPath))
  587. #endif
  588. {
  589. std::string m = "Remove failed on file: " + fullPath;
  590. cmSystemTools::ReportLastSystemError(m.c_str());
  591. }
  592. }
  593. }
  594. }
  595. }
  596. }
  597. void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
  598. cmStateEnums::TargetType targetType)
  599. {
  600. this->FindErrorMessage = "";
  601. this->OutputFile = "";
  602. std::string tmpOutputFile = "/";
  603. if (targetType == cmStateEnums::EXECUTABLE) {
  604. tmpOutputFile += targetName;
  605. tmpOutputFile +=
  606. this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  607. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  608. {
  609. tmpOutputFile +=
  610. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX");
  611. tmpOutputFile += targetName;
  612. tmpOutputFile +=
  613. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX");
  614. }
  615. // a list of directories where to search for the compilation result
  616. // at first directly in the binary dir
  617. std::vector<std::string> searchDirs;
  618. searchDirs.push_back("");
  619. const char* config =
  620. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  621. // if a config was specified try that first
  622. if (config && config[0]) {
  623. std::string tmp = "/";
  624. tmp += config;
  625. searchDirs.push_back(tmp);
  626. }
  627. searchDirs.push_back("/Debug");
  628. #if defined(__APPLE__)
  629. std::string app = "/Debug/" + targetName + ".app";
  630. searchDirs.push_back(app);
  631. #endif
  632. searchDirs.push_back("/Development");
  633. for (std::vector<std::string>::const_iterator it = searchDirs.begin();
  634. it != searchDirs.end(); ++it) {
  635. std::string command = this->BinaryDirectory;
  636. command += *it;
  637. command += tmpOutputFile;
  638. if (cmSystemTools::FileExists(command.c_str())) {
  639. this->OutputFile = cmSystemTools::CollapseFullPath(command);
  640. return;
  641. }
  642. }
  643. std::ostringstream emsg;
  644. emsg << "Unable to find the executable at any of:\n";
  645. emsg << cmWrap(" " + this->BinaryDirectory, searchDirs, tmpOutputFile, "\n")
  646. << "\n";
  647. this->FindErrorMessage = emsg.str();
  648. return;
  649. }