cmCoreTryCompile.cxx 15 KB

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