cmCoreTryCompile.cxx 15 KB

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