cmCoreTryCompile.cxx 18 KB

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