You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

425 lines
13 KiB

  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2007 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmCoreTryCompile.h"
  14. #include "cmake.h"
  15. #include "cmCacheManager.h"
  16. #include "cmGlobalGenerator.h"
  17. #include <cmsys/Directory.hxx>
  18. int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv)
  19. {
  20. this->BinaryDirectory = argv[1].c_str();
  21. this->OutputFile = "";
  22. // which signature were we called with ?
  23. this->SrcFileSignature = false;
  24. unsigned int i;
  25. const char* sourceDirectory = argv[2].c_str();
  26. const char* projectName = 0;
  27. const char* targetName = 0;
  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. ++i)
  41. {
  42. extraArgs++;
  43. cmakeFlags.push_back(argv[i]);
  44. }
  45. break;
  46. }
  47. }
  48. // look for OUTPUT_VARIABLE and store them
  49. std::string outputVariable;
  50. for (i = 3; i < argv.size(); ++i)
  51. {
  52. if (argv[i] == "OUTPUT_VARIABLE")
  53. {
  54. if ( argv.size() <= (i+1) )
  55. {
  56. cmSystemTools::Error(
  57. "OUTPUT_VARIABLE specified but there is no variable");
  58. return -1;
  59. }
  60. extraArgs += 2;
  61. outputVariable = argv[i+1];
  62. break;
  63. }
  64. }
  65. // look for COMPILE_DEFINITIONS and store them
  66. std::vector<std::string> compileFlags;
  67. for (i = 3; i < argv.size(); ++i)
  68. {
  69. if (argv[i] == "COMPILE_DEFINITIONS")
  70. {
  71. extraArgs++;
  72. for (i = i + 1; i < argv.size() && argv[i] != "CMAKE_FLAGS" &&
  73. argv[i] != "OUTPUT_VARIABLE";
  74. ++i)
  75. {
  76. extraArgs++;
  77. compileFlags.push_back(argv[i]);
  78. }
  79. break;
  80. }
  81. }
  82. // look for COPY_FILE
  83. std::string copyFile;
  84. for (i = 3; i < argv.size(); ++i)
  85. {
  86. if (argv[i] == "COPY_FILE")
  87. {
  88. if ( argv.size() <= (i+1) )
  89. {
  90. cmSystemTools::Error(
  91. "COPY_FILE specified but there is no variable");
  92. return -1;
  93. }
  94. extraArgs += 2;
  95. copyFile = argv[i+1];
  96. break;
  97. }
  98. }
  99. // do we have a srcfile signature
  100. if (argv.size() - extraArgs == 3)
  101. {
  102. this->SrcFileSignature = true;
  103. }
  104. // compute the binary dir when TRY_COMPILE is called with a src file
  105. // signature
  106. if (this->SrcFileSignature)
  107. {
  108. this->BinaryDirectory += cmake::GetCMakeFilesDirectory();
  109. this->BinaryDirectory += "/CMakeTmp";
  110. }
  111. else
  112. {
  113. // only valid for srcfile signatures
  114. if (compileFlags.size())
  115. {
  116. cmSystemTools::Error(
  117. "COMPILE_FLAGS specified on a srcdir type TRY_COMPILE");
  118. return -1;
  119. }
  120. if (copyFile.size())
  121. {
  122. cmSystemTools::Error("COPY_FILE specified on a srcdir type TRY_COMPILE");
  123. return -1;
  124. }
  125. }
  126. // make sure the binary directory exists
  127. cmSystemTools::MakeDirectory(this->BinaryDirectory.c_str());
  128. // do not allow recursive try Compiles
  129. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory())
  130. {
  131. cmSystemTools::Error(
  132. "Attempt at a recursive or nested TRY_COMPILE in directory ",
  133. this->BinaryDirectory.c_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 CMakeList file etc...
  144. // first create the directories
  145. sourceDirectory = this->BinaryDirectory.c_str();
  146. // now create a CMakeList.txt file in that directory
  147. FILE *fout = fopen(outFileName.c_str(),"w");
  148. if (!fout)
  149. {
  150. cmSystemTools::Error("Failed to create CMakeList file for ",
  151. outFileName.c_str());
  152. cmSystemTools::ReportLastSystemError("");
  153. return -1;
  154. }
  155. std::string source = argv[2];
  156. std::string ext = cmSystemTools::GetFilenameExtension(source);
  157. const char* lang =(this->Makefile->GetCMakeInstance()->GetGlobalGenerator()
  158. ->GetLanguageFromExtension(ext.c_str()));
  159. const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  160. if(def)
  161. {
  162. fprintf(fout, "SET(CMAKE_MODULE_PATH %s)\n", def);
  163. }
  164. if(lang)
  165. {
  166. fprintf(fout, "PROJECT(CMAKE_TRY_COMPILE %s)\n", lang);
  167. }
  168. else
  169. {
  170. cmOStringStream err;
  171. err << "Unknown extension \"" << ext << "\" for file \""
  172. << source << "\". TRY_COMPILE only works for enabled languages.\n"
  173. << "Currently enabled languages are:";
  174. std::vector<std::string> langs;
  175. this->Makefile->GetCMakeInstance()->GetGlobalGenerator()->
  176. GetEnabledLanguages(langs);
  177. for(std::vector<std::string>::iterator l = langs.begin();
  178. l != langs.end(); ++l)
  179. {
  180. err << " " << *l;
  181. }
  182. err << "\nSee PROJECT command for help enabling other languages.";
  183. cmSystemTools::Error(err.str().c_str());
  184. fclose(fout);
  185. return -1;
  186. }
  187. std::string langFlags = "CMAKE_";
  188. langFlags += lang;
  189. langFlags += "_FLAGS";
  190. fprintf(fout, "SET(CMAKE_VERBOSE_MAKEFILE 1)\n");
  191. fprintf(fout, "SET(CMAKE_%s_FLAGS \"", lang);
  192. const char* flags = this->Makefile->GetDefinition(langFlags.c_str());
  193. if(flags)
  194. {
  195. fprintf(fout, " %s ", flags);
  196. }
  197. fprintf(fout, " ${COMPILE_DEFINITIONS}\")\n");
  198. fprintf(fout, "INCLUDE_DIRECTORIES(${INCLUDE_DIRECTORIES})\n");
  199. fprintf(fout, "LINK_DIRECTORIES(${LINK_DIRECTORIES})\n");
  200. // handle any compile flags we need to pass on
  201. if (compileFlags.size())
  202. {
  203. fprintf(fout, "ADD_DEFINITIONS( ");
  204. for (i = 0; i < compileFlags.size(); ++i)
  205. {
  206. fprintf(fout,"%s ",compileFlags[i].c_str());
  207. }
  208. fprintf(fout, ")\n");
  209. }
  210. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  211. So the user can set CMAKE_OSX_ARCHITECTURE to i386;ppc and then set
  212. CMAKE_TRY_COMPILE_OSX_ARCHITECTURE first to i386 and then to ppc to
  213. have the tests run for each specific architecture. Since
  214. cmLocalGenerator doesn't allow building for "the other"
  215. architecture only via CMAKE_OSX_ARCHITECTURES,use to CMAKE_DO_TRY_COMPILE
  216. to enforce it for this case here.
  217. */
  218. cmakeFlags.push_back("-DCMAKE_DO_TRY_COMPILE=TRUE");
  219. if(this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_OSX_ARCHITECTURES")!=0)
  220. {
  221. std::string flag="-DCMAKE_OSX_ARCHITECTURES=";
  222. flag += this->Makefile->GetSafeDefinition(
  223. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES");
  224. cmakeFlags.push_back(flag);
  225. }
  226. else if (this->Makefile->GetDefinition("CMAKE_OSX_ARCHITECTURES")!=0)
  227. {
  228. std::string flag="-DCMAKE_OSX_ARCHITECTURES=";
  229. flag += this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  230. cmakeFlags.push_back(flag);
  231. }
  232. fprintf(fout, "ADD_EXECUTABLE(cmTryCompileExec \"%s\")\n",source.c_str());
  233. fprintf(fout,
  234. "TARGET_LINK_LIBRARIES(cmTryCompileExec ${LINK_LIBRARIES})\n");
  235. fclose(fout);
  236. projectName = "CMAKE_TRY_COMPILE";
  237. targetName = "cmTryCompileExec";
  238. // if the source is not in CMakeTmp
  239. if(source.find("CMakeTmp") == source.npos)
  240. {
  241. this->Makefile->AddCMakeDependFile(source.c_str());
  242. }
  243. }
  244. // else the srcdir bindir project target signature
  245. else
  246. {
  247. projectName = argv[3].c_str();
  248. if (argv.size() - extraArgs == 5)
  249. {
  250. targetName = argv[4].c_str();
  251. }
  252. }
  253. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  254. cmSystemTools::ResetErrorOccuredFlag();
  255. std::string output;
  256. // actually do the try compile now that everything is setup
  257. int res = this->Makefile->TryCompile(sourceDirectory,
  258. this->BinaryDirectory.c_str(),
  259. projectName,
  260. targetName,
  261. &cmakeFlags,
  262. &output);
  263. if ( erroroc )
  264. {
  265. cmSystemTools::SetErrorOccured();
  266. }
  267. // set the result var to the return value to indicate success or failure
  268. this->Makefile->AddCacheDefinition(argv[0].c_str(),
  269. (res == 0 ? "TRUE" : "FALSE"),
  270. "Result of TRY_COMPILE",
  271. cmCacheManager::INTERNAL);
  272. if ( outputVariable.size() > 0 )
  273. {
  274. this->Makefile->AddDefinition(outputVariable.c_str(), output.c_str());
  275. }
  276. if (this->SrcFileSignature)
  277. {
  278. this->FindOutputFile(targetName);
  279. if ((res==0) && (copyFile.size()))
  280. {
  281. if(!cmSystemTools::CopyFileAlways(this->OutputFile.c_str(),
  282. copyFile.c_str()))
  283. {
  284. cmSystemTools::Error("Could not COPY_FILE");
  285. return -1;
  286. }
  287. }
  288. }
  289. return res;
  290. }
  291. void cmCoreTryCompile::CleanupFiles(const char* binDir)
  292. {
  293. if ( !binDir )
  294. {
  295. return;
  296. }
  297. std::string bdir = binDir;
  298. if(bdir.find("CMakeTmp") == std::string::npos)
  299. {
  300. cmSystemTools::Error(
  301. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  302. "CMakeTmp:", binDir);
  303. return;
  304. }
  305. cmsys::Directory dir;
  306. dir.Load(binDir);
  307. size_t fileNum;
  308. std::set<cmStdString> deletedFiles;
  309. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  310. {
  311. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  312. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  313. {
  314. if(deletedFiles.find( dir.GetFile(static_cast<unsigned long>(fileNum)))
  315. == deletedFiles.end())
  316. {
  317. deletedFiles.insert(dir.GetFile(static_cast<unsigned long>(fileNum)));
  318. std::string fullPath = binDir;
  319. fullPath += "/";
  320. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  321. if(cmSystemTools::FileIsDirectory(fullPath.c_str()))
  322. {
  323. this->CleanupFiles(fullPath.c_str());
  324. }
  325. else
  326. {
  327. if(!cmSystemTools::RemoveFile(fullPath.c_str()))
  328. {
  329. std::string m = "Remove failed on file: ";
  330. m += fullPath;
  331. cmSystemTools::ReportLastSystemError(m.c_str());
  332. }
  333. }
  334. }
  335. }
  336. }
  337. }
  338. void cmCoreTryCompile::FindOutputFile(const char* targetName)
  339. {
  340. this->FindErrorMessage = "";
  341. this->OutputFile = "";
  342. std::string tmpOutputFile = "/";
  343. tmpOutputFile += targetName;
  344. tmpOutputFile +=this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  345. // a list of directories where to search for the compilation result
  346. // at first directly in the binary dir
  347. std::vector<std::string> searchDirs;
  348. searchDirs.push_back("");
  349. const char* config = this->Makefile->GetDefinition(
  350. "CMAKE_TRY_COMPILE_CONFIGURATION");
  351. // if a config was specified try that first
  352. if (config && config[0])
  353. {
  354. std::string tmp = "/";
  355. tmp += config;
  356. searchDirs.push_back(tmp);
  357. }
  358. searchDirs.push_back("/Debug");
  359. searchDirs.push_back("/Development");
  360. for(std::vector<std::string>::const_iterator it = searchDirs.begin();
  361. it != searchDirs.end();
  362. ++it)
  363. {
  364. std::string command = this->BinaryDirectory;
  365. command += *it;
  366. command += tmpOutputFile;
  367. if(cmSystemTools::FileExists(command.c_str()))
  368. {
  369. tmpOutputFile = cmSystemTools::CollapseFullPath(command.c_str());
  370. this->OutputFile = tmpOutputFile;
  371. return;
  372. }
  373. }
  374. cmOStringStream emsg;
  375. emsg << "Unable to find executable for " << this->GetName() << ": tried \"";
  376. for (unsigned int i = 0; i < searchDirs.size(); ++i)
  377. {
  378. emsg << this->BinaryDirectory << searchDirs[i] << tmpOutputFile;
  379. if (i < searchDirs.size() - 1)
  380. {
  381. emsg << "\" and \"";
  382. }
  383. else
  384. {
  385. emsg << "\".";
  386. }
  387. }
  388. this->FindErrorMessage = emsg.str();
  389. return;
  390. }