cmCoreTryCompile.cxx 25 KB

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