cmCoreTryCompile.cxx 15 KB

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