cmCoreTryCompile.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. 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. this->Makefile->IssueMessage(cmake::FATAL_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. this->Makefile->IssueMessage(cmake::FATAL_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. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  114. "COMPILE_FLAGS specified on a srcdir type TRY_COMPILE");
  115. return -1;
  116. }
  117. if (copyFile.size())
  118. {
  119. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  120. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  121. return -1;
  122. }
  123. }
  124. // make sure the binary directory exists
  125. cmSystemTools::MakeDirectory(this->BinaryDirectory.c_str());
  126. // do not allow recursive try Compiles
  127. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory())
  128. {
  129. cmOStringStream e;
  130. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  131. << " " << this->BinaryDirectory << "\n";
  132. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  133. return -1;
  134. }
  135. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  136. // which signature are we using? If we are using var srcfile bindir
  137. if (this->SrcFileSignature)
  138. {
  139. // remove any CMakeCache.txt files so we will have a clean test
  140. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  141. cmSystemTools::RemoveFile(ccFile.c_str());
  142. // we need to create a directory and CMakeList file etc...
  143. // first create the directories
  144. sourceDirectory = this->BinaryDirectory.c_str();
  145. // now create a CMakeList.txt file in that directory
  146. FILE *fout = fopen(outFileName.c_str(),"w");
  147. if (!fout)
  148. {
  149. cmOStringStream e;
  150. e << "Failed to open\n"
  151. << " " << outFileName.c_str() << "\n"
  152. << cmSystemTools::GetLastSystemError();
  153. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  154. return -1;
  155. }
  156. std::string source = argv[2];
  157. std::string ext = cmSystemTools::GetFilenameExtension(source);
  158. const char* lang =(this->Makefile->GetCMakeInstance()->GetGlobalGenerator()
  159. ->GetLanguageFromExtension(ext.c_str()));
  160. const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  161. fprintf(fout, "cmake_minimum_required(VERSION %u.%u)\n",
  162. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion());
  163. if(def)
  164. {
  165. fprintf(fout, "SET(CMAKE_MODULE_PATH %s)\n", def);
  166. }
  167. if(lang)
  168. {
  169. fprintf(fout, "PROJECT(CMAKE_TRY_COMPILE %s)\n", lang);
  170. }
  171. else
  172. {
  173. fclose(fout);
  174. cmOStringStream err;
  175. err << "Unknown extension \"" << ext << "\" for file\n"
  176. << " " << source << "\n"
  177. << "try_compile() works only for enabled languages. "
  178. << "Currently these are:\n ";
  179. std::vector<std::string> langs;
  180. this->Makefile->GetCMakeInstance()->GetGlobalGenerator()->
  181. GetEnabledLanguages(langs);
  182. for(std::vector<std::string>::iterator l = langs.begin();
  183. l != langs.end(); ++l)
  184. {
  185. err << " " << *l;
  186. }
  187. err << "\nSee project() command to enable other languages.";
  188. this->Makefile->IssueMessage(cmake::FATAL_ERROR, err.str());
  189. return -1;
  190. }
  191. std::string langFlags = "CMAKE_";
  192. langFlags += lang;
  193. langFlags += "_FLAGS";
  194. fprintf(fout, "SET(CMAKE_VERBOSE_MAKEFILE 1)\n");
  195. fprintf(fout, "SET(CMAKE_%s_FLAGS \"", lang);
  196. const char* flags = this->Makefile->GetDefinition(langFlags.c_str());
  197. if(flags)
  198. {
  199. fprintf(fout, " %s ", flags);
  200. }
  201. fprintf(fout, " ${COMPILE_DEFINITIONS}\")\n");
  202. fprintf(fout, "INCLUDE_DIRECTORIES(${INCLUDE_DIRECTORIES})\n");
  203. fprintf(fout, "SET(CMAKE_SUPPRESS_REGENERATION 1)\n");
  204. fprintf(fout, "LINK_DIRECTORIES(${LINK_DIRECTORIES})\n");
  205. // handle any compile flags we need to pass on
  206. if (compileFlags.size())
  207. {
  208. fprintf(fout, "ADD_DEFINITIONS( ");
  209. for (i = 0; i < compileFlags.size(); ++i)
  210. {
  211. fprintf(fout,"%s ",compileFlags[i].c_str());
  212. }
  213. fprintf(fout, ")\n");
  214. }
  215. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  216. So the user can set CMAKE_OSX_ARCHITECTURE to i386;ppc and then set
  217. CMAKE_TRY_COMPILE_OSX_ARCHITECTURE first to i386 and then to ppc to
  218. have the tests run for each specific architecture. Since
  219. cmLocalGenerator doesn't allow building for "the other"
  220. architecture only via CMAKE_OSX_ARCHITECTURES,use to CMAKE_DO_TRY_COMPILE
  221. to enforce it for this case here.
  222. */
  223. cmakeFlags.push_back("-DCMAKE_DO_TRY_COMPILE=TRUE");
  224. if(this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_OSX_ARCHITECTURES")!=0)
  225. {
  226. std::string flag="-DCMAKE_OSX_ARCHITECTURES=";
  227. flag += this->Makefile->GetSafeDefinition(
  228. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES");
  229. cmakeFlags.push_back(flag);
  230. }
  231. else if (this->Makefile->GetDefinition("CMAKE_OSX_ARCHITECTURES")!=0)
  232. {
  233. std::string flag="-DCMAKE_OSX_ARCHITECTURES=";
  234. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  235. cmakeFlags.push_back(flag);
  236. }
  237. /* on APPLE also pass CMAKE_OSX_SYSROOT to the try_compile */
  238. if(this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT")!=0)
  239. {
  240. std::string flag="-DCMAKE_OSX_SYSROOT=";
  241. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  242. cmakeFlags.push_back(flag);
  243. }
  244. /* on APPLE also pass CMAKE_OSX_DEPLOYMENT_TARGET to the try_compile */
  245. if(this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET")!=0)
  246. {
  247. std::string flag="-DCMAKE_OSX_DEPLOYMENT_TARGET=";
  248. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  249. cmakeFlags.push_back(flag);
  250. }
  251. fprintf(fout, "ADD_EXECUTABLE(cmTryCompileExec \"%s\")\n",source.c_str());
  252. fprintf(fout,
  253. "TARGET_LINK_LIBRARIES(cmTryCompileExec ${LINK_LIBRARIES})\n");
  254. fclose(fout);
  255. projectName = "CMAKE_TRY_COMPILE";
  256. targetName = "cmTryCompileExec";
  257. // if the source is not in CMakeTmp
  258. if(source.find("CMakeTmp") == source.npos)
  259. {
  260. this->Makefile->AddCMakeDependFile(source.c_str());
  261. }
  262. }
  263. // else the srcdir bindir project target signature
  264. else
  265. {
  266. projectName = argv[3].c_str();
  267. if (argv.size() - extraArgs == 5)
  268. {
  269. targetName = argv[4].c_str();
  270. }
  271. }
  272. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  273. cmSystemTools::ResetErrorOccuredFlag();
  274. std::string output;
  275. // actually do the try compile now that everything is setup
  276. int res = this->Makefile->TryCompile(sourceDirectory,
  277. this->BinaryDirectory.c_str(),
  278. projectName,
  279. targetName,
  280. this->SrcFileSignature,
  281. &cmakeFlags,
  282. &output);
  283. if ( erroroc )
  284. {
  285. cmSystemTools::SetErrorOccured();
  286. }
  287. // set the result var to the return value to indicate success or failure
  288. this->Makefile->AddCacheDefinition(argv[0].c_str(),
  289. (res == 0 ? "TRUE" : "FALSE"),
  290. "Result of TRY_COMPILE",
  291. cmCacheManager::INTERNAL);
  292. if ( outputVariable.size() > 0 )
  293. {
  294. this->Makefile->AddDefinition(outputVariable.c_str(), output.c_str());
  295. }
  296. if (this->SrcFileSignature)
  297. {
  298. this->FindOutputFile(targetName);
  299. if ((res==0) && (copyFile.size()))
  300. {
  301. if(this->OutputFile.empty() ||
  302. !cmSystemTools::CopyFileAlways(this->OutputFile.c_str(),
  303. copyFile.c_str()))
  304. {
  305. cmOStringStream emsg;
  306. emsg << "Cannot copy output executable\n"
  307. << " '" << this->OutputFile.c_str() << "'\n"
  308. << "to destination specified by COPY_FILE:\n"
  309. << " '" << copyFile.c_str() << "'\n";
  310. if(!this->FindErrorMessage.empty())
  311. {
  312. emsg << this->FindErrorMessage.c_str();
  313. }
  314. this->Makefile->IssueMessage(cmake::FATAL_ERROR, emsg.str());
  315. return -1;
  316. }
  317. }
  318. }
  319. return res;
  320. }
  321. void cmCoreTryCompile::CleanupFiles(const char* binDir)
  322. {
  323. if ( !binDir )
  324. {
  325. return;
  326. }
  327. std::string bdir = binDir;
  328. if(bdir.find("CMakeTmp") == std::string::npos)
  329. {
  330. cmSystemTools::Error(
  331. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  332. "CMakeTmp:", binDir);
  333. return;
  334. }
  335. cmsys::Directory dir;
  336. dir.Load(binDir);
  337. size_t fileNum;
  338. std::set<cmStdString> deletedFiles;
  339. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  340. {
  341. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  342. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  343. {
  344. if(deletedFiles.find( dir.GetFile(static_cast<unsigned long>(fileNum)))
  345. == deletedFiles.end())
  346. {
  347. deletedFiles.insert(dir.GetFile(static_cast<unsigned long>(fileNum)));
  348. std::string fullPath = binDir;
  349. fullPath += "/";
  350. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  351. if(cmSystemTools::FileIsDirectory(fullPath.c_str()))
  352. {
  353. this->CleanupFiles(fullPath.c_str());
  354. }
  355. else
  356. {
  357. if(!cmSystemTools::RemoveFile(fullPath.c_str()))
  358. {
  359. bool removed = false;
  360. int numAttempts = 0;
  361. // sometimes anti-virus software hangs on to
  362. // new files and we can not delete them, so try
  363. // 5 times with .5 second delay between tries.
  364. while(!removed && numAttempts < 5)
  365. {
  366. cmSystemTools::Delay(500);
  367. if(cmSystemTools::RemoveFile(fullPath.c_str()))
  368. {
  369. removed = true;
  370. }
  371. numAttempts++;
  372. }
  373. if(!removed)
  374. {
  375. std::string m = "Remove failed on file: ";
  376. m += fullPath;
  377. cmSystemTools::ReportLastSystemError(m.c_str());
  378. }
  379. }
  380. }
  381. }
  382. }
  383. }
  384. }
  385. void cmCoreTryCompile::FindOutputFile(const char* targetName)
  386. {
  387. this->FindErrorMessage = "";
  388. this->OutputFile = "";
  389. std::string tmpOutputFile = "/";
  390. tmpOutputFile += targetName;
  391. tmpOutputFile +=this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  392. // a list of directories where to search for the compilation result
  393. // at first directly in the binary dir
  394. std::vector<std::string> searchDirs;
  395. searchDirs.push_back("");
  396. const char* config = this->Makefile->GetDefinition(
  397. "CMAKE_TRY_COMPILE_CONFIGURATION");
  398. // if a config was specified try that first
  399. if (config && config[0])
  400. {
  401. std::string tmp = "/";
  402. tmp += config;
  403. searchDirs.push_back(tmp);
  404. }
  405. searchDirs.push_back("/Debug");
  406. searchDirs.push_back("/Development");
  407. for(std::vector<std::string>::const_iterator it = searchDirs.begin();
  408. it != searchDirs.end();
  409. ++it)
  410. {
  411. std::string command = this->BinaryDirectory;
  412. command += *it;
  413. command += tmpOutputFile;
  414. if(cmSystemTools::FileExists(command.c_str()))
  415. {
  416. tmpOutputFile = cmSystemTools::CollapseFullPath(command.c_str());
  417. this->OutputFile = tmpOutputFile;
  418. return;
  419. }
  420. }
  421. cmOStringStream emsg;
  422. emsg << "Unable to find the executable at any of:\n";
  423. for (unsigned int i = 0; i < searchDirs.size(); ++i)
  424. {
  425. emsg << " " << this->BinaryDirectory << searchDirs[i]
  426. << tmpOutputFile << "\n";
  427. }
  428. this->FindErrorMessage = emsg.str();
  429. return;
  430. }