cmCoreTryCompile.cxx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 "cmCacheManager.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmExportTryCompileFileGenerator.h"
  15. #include <cmsys/Directory.hxx>
  16. #include <assert.h>
  17. int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv)
  18. {
  19. this->BinaryDirectory = argv[1].c_str();
  20. this->OutputFile = "";
  21. // which signature were we called with ?
  22. this->SrcFileSignature = true;
  23. const char* sourceDirectory = argv[2].c_str();
  24. const char* projectName = 0;
  25. const char* targetName = 0;
  26. std::vector<std::string> cmakeFlags;
  27. std::vector<std::string> compileDefs;
  28. std::string outputVariable;
  29. std::string copyFile;
  30. std::vector<cmTarget*> targets;
  31. std::string libsToLink = " ";
  32. bool useOldLinkLibs = true;
  33. char targetNameBuf[64];
  34. bool didOutputVariable = false;
  35. bool didCopyFile = false;
  36. bool useSources = argv[2] == "SOURCES";
  37. std::vector<std::string> sources;
  38. enum Doing { DoingNone, DoingCMakeFlags, DoingCompileDefinitions,
  39. DoingLinkLibraries, DoingOutputVariable, DoingCopyFile,
  40. DoingSources };
  41. Doing doing = useSources? DoingSources : DoingNone;
  42. for(size_t i=3; i < argv.size(); ++i)
  43. {
  44. if(argv[i] == "CMAKE_FLAGS")
  45. {
  46. doing = DoingCMakeFlags;
  47. // CMAKE_FLAGS is the first argument because we need an argv[0] that
  48. // is not used, so it matches regular command line parsing which has
  49. // the program name as arg 0
  50. cmakeFlags.push_back(argv[i]);
  51. }
  52. else if(argv[i] == "COMPILE_DEFINITIONS")
  53. {
  54. doing = DoingCompileDefinitions;
  55. }
  56. else if(argv[i] == "LINK_LIBRARIES")
  57. {
  58. doing = DoingLinkLibraries;
  59. useOldLinkLibs = false;
  60. }
  61. else if(argv[i] == "OUTPUT_VARIABLE")
  62. {
  63. doing = DoingOutputVariable;
  64. didOutputVariable = true;
  65. }
  66. else if(argv[i] == "COPY_FILE")
  67. {
  68. doing = DoingCopyFile;
  69. didCopyFile = true;
  70. }
  71. else if(doing == DoingCMakeFlags)
  72. {
  73. cmakeFlags.push_back(argv[i]);
  74. }
  75. else if(doing == DoingCompileDefinitions)
  76. {
  77. compileDefs.push_back(argv[i]);
  78. }
  79. else if(doing == DoingLinkLibraries)
  80. {
  81. libsToLink += "\"" + cmSystemTools::TrimWhitespace(argv[i]) + "\" ";
  82. if(cmTarget *tgt = this->Makefile->FindTargetToUse(argv[i].c_str()))
  83. {
  84. switch(tgt->GetType())
  85. {
  86. case cmTarget::SHARED_LIBRARY:
  87. case cmTarget::STATIC_LIBRARY:
  88. case cmTarget::UNKNOWN_LIBRARY:
  89. break;
  90. case cmTarget::EXECUTABLE:
  91. if (tgt->IsExecutableWithExports())
  92. {
  93. break;
  94. }
  95. default:
  96. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  97. "Only libraries may be used as try_compile IMPORTED "
  98. "LINK_LIBRARIES. Got " + std::string(tgt->GetName()) + " of "
  99. "type " + tgt->GetTargetTypeName(tgt->GetType()) + ".");
  100. return -1;
  101. }
  102. if (tgt->IsImported())
  103. {
  104. targets.push_back(tgt);
  105. }
  106. }
  107. }
  108. else if(doing == DoingOutputVariable)
  109. {
  110. outputVariable = argv[i].c_str();
  111. doing = DoingNone;
  112. }
  113. else if(doing == DoingCopyFile)
  114. {
  115. copyFile = argv[i].c_str();
  116. doing = DoingNone;
  117. }
  118. else if(doing == DoingSources)
  119. {
  120. sources.push_back(argv[i]);
  121. }
  122. else if(i == 3)
  123. {
  124. this->SrcFileSignature = false;
  125. projectName = argv[i].c_str();
  126. }
  127. else if(i == 4 && !this->SrcFileSignature)
  128. {
  129. targetName = argv[i].c_str();
  130. }
  131. else
  132. {
  133. cmOStringStream m;
  134. m << "try_compile given unknown argument \"" << argv[i] << "\".";
  135. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, m.str());
  136. }
  137. }
  138. if(didCopyFile && copyFile.empty())
  139. {
  140. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  141. "COPY_FILE must be followed by a file path");
  142. return -1;
  143. }
  144. if(didOutputVariable && outputVariable.empty())
  145. {
  146. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  147. "OUTPUT_VARIABLE must be followed by a variable name");
  148. return -1;
  149. }
  150. if(useSources && sources.empty())
  151. {
  152. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  153. "SOURCES must be followed by at least one source file");
  154. return -1;
  155. }
  156. // compute the binary dir when TRY_COMPILE is called with a src file
  157. // signature
  158. if (this->SrcFileSignature)
  159. {
  160. this->BinaryDirectory += cmake::GetCMakeFilesDirectory();
  161. this->BinaryDirectory += "/CMakeTmp";
  162. }
  163. else
  164. {
  165. // only valid for srcfile signatures
  166. if (compileDefs.size())
  167. {
  168. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  169. "COMPILE_DEFINITIONS specified on a srcdir type TRY_COMPILE");
  170. return -1;
  171. }
  172. if (copyFile.size())
  173. {
  174. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  175. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  176. return -1;
  177. }
  178. }
  179. // make sure the binary directory exists
  180. cmSystemTools::MakeDirectory(this->BinaryDirectory.c_str());
  181. // do not allow recursive try Compiles
  182. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory())
  183. {
  184. cmOStringStream e;
  185. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  186. << " " << this->BinaryDirectory << "\n";
  187. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  188. return -1;
  189. }
  190. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  191. // which signature are we using? If we are using var srcfile bindir
  192. if (this->SrcFileSignature)
  193. {
  194. // remove any CMakeCache.txt files so we will have a clean test
  195. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  196. cmSystemTools::RemoveFile(ccFile.c_str());
  197. // Choose sources.
  198. if(!useSources)
  199. {
  200. sources.push_back(argv[2]);
  201. }
  202. // Detect languages to enable.
  203. cmGlobalGenerator* gg =
  204. this->Makefile->GetCMakeInstance()->GetGlobalGenerator();
  205. std::set<std::string> testLangs;
  206. for(std::vector<std::string>::iterator si = sources.begin();
  207. si != sources.end(); ++si)
  208. {
  209. std::string ext = cmSystemTools::GetFilenameLastExtension(*si);
  210. if(const char* lang = gg->GetLanguageFromExtension(ext.c_str()))
  211. {
  212. testLangs.insert(lang);
  213. }
  214. else
  215. {
  216. cmOStringStream err;
  217. err << "Unknown extension \"" << ext << "\" for file\n"
  218. << " " << *si << "\n"
  219. << "try_compile() works only for enabled languages. "
  220. << "Currently these are:\n ";
  221. std::vector<std::string> langs;
  222. gg->GetEnabledLanguages(langs);
  223. for(std::vector<std::string>::iterator l = langs.begin();
  224. l != langs.end(); ++l)
  225. {
  226. err << " " << *l;
  227. }
  228. err << "\nSee project() command to enable other languages.";
  229. this->Makefile->IssueMessage(cmake::FATAL_ERROR, err.str());
  230. return -1;
  231. }
  232. }
  233. // we need to create a directory and CMakeLists file etc...
  234. // first create the directories
  235. sourceDirectory = this->BinaryDirectory.c_str();
  236. // now create a CMakeLists.txt file in that directory
  237. FILE *fout = fopen(outFileName.c_str(),"w");
  238. if (!fout)
  239. {
  240. cmOStringStream e;
  241. e << "Failed to open\n"
  242. << " " << outFileName.c_str() << "\n"
  243. << cmSystemTools::GetLastSystemError();
  244. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  245. return -1;
  246. }
  247. const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  248. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  249. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  250. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  251. if(def)
  252. {
  253. fprintf(fout, "SET(CMAKE_MODULE_PATH %s)\n", def);
  254. }
  255. std::string projectLangs;
  256. for(std::set<std::string>::iterator li = testLangs.begin();
  257. li != testLangs.end(); ++li)
  258. {
  259. projectLangs += " " + *li;
  260. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  261. std::string rulesOverrideLang = rulesOverrideBase + "_" + *li;
  262. if(const char* rulesOverridePath =
  263. this->Makefile->GetDefinition(rulesOverrideLang.c_str()))
  264. {
  265. fprintf(fout, "SET(%s \"%s\")\n",
  266. rulesOverrideLang.c_str(), rulesOverridePath);
  267. }
  268. else if(const char* rulesOverridePath2 =
  269. this->Makefile->GetDefinition(rulesOverrideBase.c_str()))
  270. {
  271. fprintf(fout, "SET(%s \"%s\")\n",
  272. rulesOverrideBase.c_str(), rulesOverridePath2);
  273. }
  274. }
  275. fprintf(fout, "PROJECT(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  276. fprintf(fout, "SET(CMAKE_VERBOSE_MAKEFILE 1)\n");
  277. for(std::set<std::string>::iterator li = testLangs.begin();
  278. li != testLangs.end(); ++li)
  279. {
  280. fprintf(fout, "SET(CMAKE_%s_FLAGS \"", li->c_str());
  281. std::string langFlags = "CMAKE_" + *li + "_FLAGS";
  282. if(const char* flags = this->Makefile->GetDefinition(langFlags.c_str()))
  283. {
  284. fprintf(fout, " %s ", flags);
  285. }
  286. fprintf(fout, " ${COMPILE_DEFINITIONS}\")\n");
  287. }
  288. fprintf(fout, "INCLUDE_DIRECTORIES(${INCLUDE_DIRECTORIES})\n");
  289. fprintf(fout, "SET(CMAKE_SUPPRESS_REGENERATION 1)\n");
  290. fprintf(fout, "LINK_DIRECTORIES(${LINK_DIRECTORIES})\n");
  291. // handle any compile flags we need to pass on
  292. if (compileDefs.size())
  293. {
  294. fprintf(fout, "ADD_DEFINITIONS( ");
  295. for (size_t i = 0; i < compileDefs.size(); ++i)
  296. {
  297. fprintf(fout,"%s ",compileDefs[i].c_str());
  298. }
  299. fprintf(fout, ")\n");
  300. }
  301. /* Use a random file name to avoid rapid creation and deletion
  302. of the same executable name (some filesystems fail on that). */
  303. sprintf(targetNameBuf, "cmTryCompileExec%u",
  304. cmSystemTools::RandomSeed());
  305. targetName = targetNameBuf;
  306. if (!targets.empty())
  307. {
  308. std::string fname = "/" + std::string(targetName) + "Targets.cmake";
  309. cmExportTryCompileFileGenerator tcfg;
  310. tcfg.SetExportFile((this->BinaryDirectory + fname).c_str());
  311. tcfg.SetExports(targets);
  312. tcfg.SetConfig(this->Makefile->GetDefinition(
  313. "CMAKE_TRY_COMPILE_CONFIGURATION"));
  314. if(!tcfg.GenerateImportFile())
  315. {
  316. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  317. "could not write export file.");
  318. fclose(fout);
  319. return -1;
  320. }
  321. fprintf(fout,
  322. "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  323. fname.c_str());
  324. }
  325. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  326. So the user can set CMAKE_OSX_ARCHITECTURE to i386;ppc and then set
  327. CMAKE_TRY_COMPILE_OSX_ARCHITECTURE first to i386 and then to ppc to
  328. have the tests run for each specific architecture. Since
  329. cmLocalGenerator doesn't allow building for "the other"
  330. architecture only via CMAKE_OSX_ARCHITECTURES.
  331. */
  332. if(this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_OSX_ARCHITECTURES")!=0)
  333. {
  334. std::string flag="-DCMAKE_OSX_ARCHITECTURES=";
  335. flag += this->Makefile->GetSafeDefinition(
  336. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES");
  337. cmakeFlags.push_back(flag);
  338. }
  339. else if (this->Makefile->GetDefinition("CMAKE_OSX_ARCHITECTURES")!=0)
  340. {
  341. std::string flag="-DCMAKE_OSX_ARCHITECTURES=";
  342. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  343. cmakeFlags.push_back(flag);
  344. }
  345. /* on APPLE also pass CMAKE_OSX_SYSROOT to the try_compile */
  346. if(this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT")!=0)
  347. {
  348. std::string flag="-DCMAKE_OSX_SYSROOT=";
  349. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  350. cmakeFlags.push_back(flag);
  351. }
  352. /* on APPLE also pass CMAKE_OSX_DEPLOYMENT_TARGET to the try_compile */
  353. if(this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET")!=0)
  354. {
  355. std::string flag="-DCMAKE_OSX_DEPLOYMENT_TARGET=";
  356. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  357. cmakeFlags.push_back(flag);
  358. }
  359. if(this->Makefile->GetDefinition("CMAKE_POSITION_INDEPENDENT_CODE")!=0)
  360. {
  361. fprintf(fout, "SET(CMAKE_POSITION_INDEPENDENT_CODE \"ON\")\n");
  362. }
  363. /* Put the executable at a known location (for COPY_FILE). */
  364. fprintf(fout, "SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  365. this->BinaryDirectory.c_str());
  366. /* Create the actual executable. */
  367. fprintf(fout, "ADD_EXECUTABLE(%s", targetName);
  368. for(std::vector<std::string>::iterator si = sources.begin();
  369. si != sources.end(); ++si)
  370. {
  371. fprintf(fout, " \"%s\"", si->c_str());
  372. // Add dependencies on any non-temporary sources.
  373. if(si->find("CMakeTmp") == si->npos)
  374. {
  375. this->Makefile->AddCMakeDependFile(*si);
  376. }
  377. }
  378. fprintf(fout, ")\n");
  379. if (useOldLinkLibs)
  380. {
  381. fprintf(fout,
  382. "TARGET_LINK_LIBRARIES(%s ${LINK_LIBRARIES})\n",targetName);
  383. }
  384. else
  385. {
  386. fprintf(fout, "TARGET_LINK_LIBRARIES(%s %s)\n",
  387. targetName,
  388. libsToLink.c_str());
  389. }
  390. fclose(fout);
  391. projectName = "CMAKE_TRY_COMPILE";
  392. }
  393. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  394. cmSystemTools::ResetErrorOccuredFlag();
  395. std::string output;
  396. // actually do the try compile now that everything is setup
  397. int res = this->Makefile->TryCompile(sourceDirectory,
  398. this->BinaryDirectory.c_str(),
  399. projectName,
  400. targetName,
  401. this->SrcFileSignature,
  402. &cmakeFlags,
  403. &output);
  404. if ( erroroc )
  405. {
  406. cmSystemTools::SetErrorOccured();
  407. }
  408. // set the result var to the return value to indicate success or failure
  409. this->Makefile->AddCacheDefinition(argv[0].c_str(),
  410. (res == 0 ? "TRUE" : "FALSE"),
  411. "Result of TRY_COMPILE",
  412. cmCacheManager::INTERNAL);
  413. if ( outputVariable.size() > 0 )
  414. {
  415. this->Makefile->AddDefinition(outputVariable.c_str(), output.c_str());
  416. }
  417. if (this->SrcFileSignature)
  418. {
  419. this->FindOutputFile(targetName);
  420. if ((res==0) && (copyFile.size()))
  421. {
  422. if(this->OutputFile.empty() ||
  423. !cmSystemTools::CopyFileAlways(this->OutputFile.c_str(),
  424. copyFile.c_str()))
  425. {
  426. cmOStringStream emsg;
  427. emsg << "Cannot copy output executable\n"
  428. << " '" << this->OutputFile.c_str() << "'\n"
  429. << "to destination specified by COPY_FILE:\n"
  430. << " '" << copyFile.c_str() << "'\n";
  431. if(!this->FindErrorMessage.empty())
  432. {
  433. emsg << this->FindErrorMessage.c_str();
  434. }
  435. this->Makefile->IssueMessage(cmake::FATAL_ERROR, emsg.str());
  436. return -1;
  437. }
  438. }
  439. }
  440. return res;
  441. }
  442. void cmCoreTryCompile::CleanupFiles(const char* binDir)
  443. {
  444. if ( !binDir )
  445. {
  446. return;
  447. }
  448. std::string bdir = binDir;
  449. if(bdir.find("CMakeTmp") == std::string::npos)
  450. {
  451. cmSystemTools::Error(
  452. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  453. "CMakeTmp:", binDir);
  454. return;
  455. }
  456. cmsys::Directory dir;
  457. dir.Load(binDir);
  458. size_t fileNum;
  459. std::set<cmStdString> deletedFiles;
  460. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  461. {
  462. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  463. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  464. {
  465. if(deletedFiles.find( dir.GetFile(static_cast<unsigned long>(fileNum)))
  466. == deletedFiles.end())
  467. {
  468. deletedFiles.insert(dir.GetFile(static_cast<unsigned long>(fileNum)));
  469. std::string fullPath = binDir;
  470. fullPath += "/";
  471. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  472. if(cmSystemTools::FileIsDirectory(fullPath.c_str()))
  473. {
  474. this->CleanupFiles(fullPath.c_str());
  475. cmSystemTools::RemoveADirectory(fullPath.c_str());
  476. }
  477. else
  478. {
  479. // Sometimes anti-virus software hangs on to new files so we
  480. // cannot delete them immediately. Try a few times.
  481. int tries = 5;
  482. while(!cmSystemTools::RemoveFile(fullPath.c_str()) &&
  483. --tries && cmSystemTools::FileExists(fullPath.c_str()))
  484. {
  485. cmSystemTools::Delay(500);
  486. }
  487. if(tries == 0)
  488. {
  489. std::string m = "Remove failed on file: " + fullPath;
  490. cmSystemTools::ReportLastSystemError(m.c_str());
  491. }
  492. }
  493. }
  494. }
  495. }
  496. }
  497. void cmCoreTryCompile::FindOutputFile(const char* targetName)
  498. {
  499. this->FindErrorMessage = "";
  500. this->OutputFile = "";
  501. std::string tmpOutputFile = "/";
  502. tmpOutputFile += targetName;
  503. tmpOutputFile +=this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  504. // a list of directories where to search for the compilation result
  505. // at first directly in the binary dir
  506. std::vector<std::string> searchDirs;
  507. searchDirs.push_back("");
  508. const char* config = this->Makefile->GetDefinition(
  509. "CMAKE_TRY_COMPILE_CONFIGURATION");
  510. // if a config was specified try that first
  511. if (config && config[0])
  512. {
  513. std::string tmp = "/";
  514. tmp += config;
  515. searchDirs.push_back(tmp);
  516. }
  517. searchDirs.push_back("/Debug");
  518. searchDirs.push_back("/Development");
  519. for(std::vector<std::string>::const_iterator it = searchDirs.begin();
  520. it != searchDirs.end();
  521. ++it)
  522. {
  523. std::string command = this->BinaryDirectory;
  524. command += *it;
  525. command += tmpOutputFile;
  526. if(cmSystemTools::FileExists(command.c_str()))
  527. {
  528. tmpOutputFile = cmSystemTools::CollapseFullPath(command.c_str());
  529. this->OutputFile = tmpOutputFile;
  530. return;
  531. }
  532. }
  533. cmOStringStream emsg;
  534. emsg << "Unable to find the executable at any of:\n";
  535. for (unsigned int i = 0; i < searchDirs.size(); ++i)
  536. {
  537. emsg << " " << this->BinaryDirectory << searchDirs[i]
  538. << tmpOutputFile << "\n";
  539. }
  540. this->FindErrorMessage = emsg.str();
  541. return;
  542. }