cmCoreTryCompile.cxx 23 KB

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