cmCoreTryCompile.cxx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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 "cmAlgorithms.h"
  12. #include "cmExportTryCompileFileGenerator.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmOutputConverter.h"
  15. #include "cmake.h"
  16. #include <cmsys/Directory.hxx>
  17. #include <assert.h>
  18. static std::string const kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN =
  19. "CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN";
  20. static std::string const kCMAKE_C_COMPILER_TARGET = "CMAKE_C_COMPILER_TARGET";
  21. static std::string const kCMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN =
  22. "CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN";
  23. static std::string const kCMAKE_CXX_COMPILER_TARGET =
  24. "CMAKE_CXX_COMPILER_TARGET";
  25. static std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
  26. static std::string const kCMAKE_LINK_SEARCH_END_STATIC =
  27. "CMAKE_LINK_SEARCH_END_STATIC";
  28. static std::string const kCMAKE_LINK_SEARCH_START_STATIC =
  29. "CMAKE_LINK_SEARCH_START_STATIC";
  30. static std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
  31. static std::string const kCMAKE_OSX_DEPLOYMENT_TARGET =
  32. "CMAKE_OSX_DEPLOYMENT_TARGET";
  33. static std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
  34. static std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
  35. "CMAKE_POSITION_INDEPENDENT_CODE";
  36. static std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
  37. static std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
  38. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
  39. static std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
  40. "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
  41. int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
  42. bool isTryRun)
  43. {
  44. this->BinaryDirectory = argv[1].c_str();
  45. this->OutputFile = "";
  46. // which signature were we called with ?
  47. this->SrcFileSignature = true;
  48. cmState::TargetType targetType = cmState::EXECUTABLE;
  49. const char* tt =
  50. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_TARGET_TYPE");
  51. if (!isTryRun && tt && *tt) {
  52. if (strcmp(tt, cmState::GetTargetTypeName(cmState::EXECUTABLE)) == 0) {
  53. targetType = cmState::EXECUTABLE;
  54. } else if (strcmp(tt, cmState::GetTargetTypeName(
  55. cmState::STATIC_LIBRARY)) == 0) {
  56. targetType = cmState::STATIC_LIBRARY;
  57. } else {
  58. this->Makefile->IssueMessage(
  59. cmake::FATAL_ERROR, std::string("Invalid value '") + tt +
  60. "' for "
  61. "CMAKE_TRY_COMPILE_TARGET_TYPE. Only "
  62. "'" +
  63. cmState::GetTargetTypeName(cmState::EXECUTABLE) + "' and "
  64. "'" +
  65. cmState::GetTargetTypeName(cmState::STATIC_LIBRARY) +
  66. "' "
  67. "are allowed.");
  68. return -1;
  69. }
  70. }
  71. const char* sourceDirectory = argv[2].c_str();
  72. const char* projectName = CM_NULLPTR;
  73. std::string targetName;
  74. std::vector<std::string> cmakeFlags(1, "CMAKE_FLAGS"); // fake argv[0]
  75. std::vector<std::string> compileDefs;
  76. std::string outputVariable;
  77. std::string copyFile;
  78. std::string copyFileError;
  79. std::vector<std::string> targets;
  80. std::string libsToLink = " ";
  81. bool useOldLinkLibs = true;
  82. char targetNameBuf[64];
  83. bool didOutputVariable = false;
  84. bool didCopyFile = false;
  85. bool didCopyFileError = false;
  86. bool useSources = argv[2] == "SOURCES";
  87. std::vector<std::string> sources;
  88. enum Doing
  89. {
  90. DoingNone,
  91. DoingCMakeFlags,
  92. DoingCompileDefinitions,
  93. DoingLinkLibraries,
  94. DoingOutputVariable,
  95. DoingCopyFile,
  96. DoingCopyFileError,
  97. DoingSources
  98. };
  99. Doing doing = useSources ? DoingSources : DoingNone;
  100. for (size_t i = 3; i < argv.size(); ++i) {
  101. if (argv[i] == "CMAKE_FLAGS") {
  102. doing = DoingCMakeFlags;
  103. } else if (argv[i] == "COMPILE_DEFINITIONS") {
  104. doing = DoingCompileDefinitions;
  105. } else if (argv[i] == "LINK_LIBRARIES") {
  106. doing = DoingLinkLibraries;
  107. useOldLinkLibs = false;
  108. } else if (argv[i] == "OUTPUT_VARIABLE") {
  109. doing = DoingOutputVariable;
  110. didOutputVariable = true;
  111. } else if (argv[i] == "COPY_FILE") {
  112. doing = DoingCopyFile;
  113. didCopyFile = true;
  114. } else if (argv[i] == "COPY_FILE_ERROR") {
  115. doing = DoingCopyFileError;
  116. didCopyFileError = true;
  117. } else if (doing == DoingCMakeFlags) {
  118. cmakeFlags.push_back(argv[i]);
  119. } else if (doing == DoingCompileDefinitions) {
  120. compileDefs.push_back(argv[i]);
  121. } else if (doing == DoingLinkLibraries) {
  122. libsToLink += "\"" + cmSystemTools::TrimWhitespace(argv[i]) + "\" ";
  123. if (cmTarget* tgt = this->Makefile->FindTargetToUse(argv[i])) {
  124. switch (tgt->GetType()) {
  125. case cmState::SHARED_LIBRARY:
  126. case cmState::STATIC_LIBRARY:
  127. case cmState::INTERFACE_LIBRARY:
  128. case cmState::UNKNOWN_LIBRARY:
  129. break;
  130. case cmState::EXECUTABLE:
  131. if (tgt->IsExecutableWithExports()) {
  132. break;
  133. }
  134. default:
  135. this->Makefile->IssueMessage(
  136. cmake::FATAL_ERROR,
  137. "Only libraries may be used as try_compile or try_run IMPORTED "
  138. "LINK_LIBRARIES. Got " +
  139. std::string(tgt->GetName()) + " of "
  140. "type " +
  141. cmState::GetTargetTypeName(tgt->GetType()) + ".");
  142. return -1;
  143. }
  144. if (tgt->IsImported()) {
  145. targets.push_back(argv[i]);
  146. }
  147. }
  148. } else if (doing == DoingOutputVariable) {
  149. outputVariable = argv[i].c_str();
  150. doing = DoingNone;
  151. } else if (doing == DoingCopyFile) {
  152. copyFile = argv[i].c_str();
  153. doing = DoingNone;
  154. } else if (doing == DoingCopyFileError) {
  155. copyFileError = argv[i].c_str();
  156. doing = DoingNone;
  157. } else if (doing == DoingSources) {
  158. sources.push_back(argv[i]);
  159. } else if (i == 3) {
  160. this->SrcFileSignature = false;
  161. projectName = argv[i].c_str();
  162. } else if (i == 4 && !this->SrcFileSignature) {
  163. targetName = argv[i].c_str();
  164. } else {
  165. std::ostringstream m;
  166. m << "try_compile given unknown argument \"" << argv[i] << "\".";
  167. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, m.str());
  168. }
  169. }
  170. if (didCopyFile && copyFile.empty()) {
  171. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  172. "COPY_FILE must be followed by a file path");
  173. return -1;
  174. }
  175. if (didCopyFileError && copyFileError.empty()) {
  176. this->Makefile->IssueMessage(
  177. cmake::FATAL_ERROR,
  178. "COPY_FILE_ERROR must be followed by a variable name");
  179. return -1;
  180. }
  181. if (didCopyFileError && !didCopyFile) {
  182. this->Makefile->IssueMessage(
  183. cmake::FATAL_ERROR, "COPY_FILE_ERROR may be used only with COPY_FILE");
  184. return -1;
  185. }
  186. if (didOutputVariable && outputVariable.empty()) {
  187. this->Makefile->IssueMessage(
  188. cmake::FATAL_ERROR,
  189. "OUTPUT_VARIABLE must be followed by a variable name");
  190. return -1;
  191. }
  192. if (useSources && sources.empty()) {
  193. this->Makefile->IssueMessage(
  194. cmake::FATAL_ERROR,
  195. "SOURCES must be followed by at least one source file");
  196. return -1;
  197. }
  198. // compute the binary dir when TRY_COMPILE is called with a src file
  199. // signature
  200. if (this->SrcFileSignature) {
  201. this->BinaryDirectory += cmake::GetCMakeFilesDirectory();
  202. this->BinaryDirectory += "/CMakeTmp";
  203. } else {
  204. // only valid for srcfile signatures
  205. if (!compileDefs.empty()) {
  206. this->Makefile->IssueMessage(
  207. cmake::FATAL_ERROR,
  208. "COMPILE_DEFINITIONS specified on a srcdir type TRY_COMPILE");
  209. return -1;
  210. }
  211. if (!copyFile.empty()) {
  212. this->Makefile->IssueMessage(
  213. cmake::FATAL_ERROR,
  214. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  215. return -1;
  216. }
  217. }
  218. // make sure the binary directory exists
  219. cmSystemTools::MakeDirectory(this->BinaryDirectory.c_str());
  220. // do not allow recursive try Compiles
  221. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
  222. std::ostringstream e;
  223. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  224. << " " << this->BinaryDirectory << "\n";
  225. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  226. return -1;
  227. }
  228. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  229. // which signature are we using? If we are using var srcfile bindir
  230. if (this->SrcFileSignature) {
  231. // remove any CMakeCache.txt files so we will have a clean test
  232. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  233. cmSystemTools::RemoveFile(ccFile);
  234. // Choose sources.
  235. if (!useSources) {
  236. sources.push_back(argv[2]);
  237. }
  238. // Detect languages to enable.
  239. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  240. std::set<std::string> testLangs;
  241. for (std::vector<std::string>::iterator si = sources.begin();
  242. si != sources.end(); ++si) {
  243. std::string ext = cmSystemTools::GetFilenameLastExtension(*si);
  244. std::string lang = gg->GetLanguageFromExtension(ext.c_str());
  245. if (!lang.empty()) {
  246. testLangs.insert(lang);
  247. } else {
  248. std::ostringstream err;
  249. err << "Unknown extension \"" << ext << "\" for file\n"
  250. << " " << *si << "\n"
  251. << "try_compile() works only for enabled languages. "
  252. << "Currently these are:\n ";
  253. std::vector<std::string> langs;
  254. gg->GetEnabledLanguages(langs);
  255. err << cmJoin(langs, " ");
  256. err << "\nSee project() command to enable other languages.";
  257. this->Makefile->IssueMessage(cmake::FATAL_ERROR, err.str());
  258. return -1;
  259. }
  260. }
  261. std::string const tcConfig =
  262. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  263. // we need to create a directory and CMakeLists file etc...
  264. // first create the directories
  265. sourceDirectory = this->BinaryDirectory.c_str();
  266. // now create a CMakeLists.txt file in that directory
  267. FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
  268. if (!fout) {
  269. std::ostringstream e;
  270. /* clang-format off */
  271. e << "Failed to open\n"
  272. << " " << outFileName << "\n"
  273. << cmSystemTools::GetLastSystemError();
  274. /* clang-format on */
  275. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  276. return -1;
  277. }
  278. const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  279. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  280. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  281. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  282. if (def) {
  283. fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def);
  284. }
  285. std::string projectLangs;
  286. for (std::set<std::string>::iterator li = testLangs.begin();
  287. li != testLangs.end(); ++li) {
  288. projectLangs += " " + *li;
  289. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  290. std::string rulesOverrideLang = rulesOverrideBase + "_" + *li;
  291. if (const char* rulesOverridePath =
  292. this->Makefile->GetDefinition(rulesOverrideLang)) {
  293. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
  294. rulesOverridePath);
  295. } else if (const char* rulesOverridePath2 =
  296. this->Makefile->GetDefinition(rulesOverrideBase)) {
  297. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
  298. rulesOverridePath2);
  299. }
  300. }
  301. fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  302. fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
  303. for (std::set<std::string>::iterator li = testLangs.begin();
  304. li != testLangs.end(); ++li) {
  305. std::string langFlags = "CMAKE_" + *li + "_FLAGS";
  306. const char* flags = this->Makefile->GetDefinition(langFlags);
  307. fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li->c_str(),
  308. cmOutputConverter::EscapeForCMake(flags ? flags : "").c_str());
  309. fprintf(fout, "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
  310. " ${COMPILE_DEFINITIONS}\")\n",
  311. li->c_str(), li->c_str());
  312. static std::string const cfgDefault = "DEBUG";
  313. std::string const cfg =
  314. !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
  315. std::string const langFlagsCfg = "CMAKE_" + *li + "_FLAGS_" + cfg;
  316. const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
  317. fprintf(
  318. fout, "set(%s %s)\n", langFlagsCfg.c_str(),
  319. cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "").c_str());
  320. }
  321. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
  322. case cmPolicies::WARN:
  323. if (this->Makefile->PolicyOptionalWarningEnabled(
  324. "CMAKE_POLICY_WARNING_CMP0056")) {
  325. std::ostringstream w;
  326. /* clang-format off */
  327. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0056) << "\n"
  328. "For compatibility with older versions of CMake, try_compile "
  329. "is not honoring caller link flags (e.g. CMAKE_EXE_LINKER_FLAGS) "
  330. "in the test project."
  331. ;
  332. /* clang-format on */
  333. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  334. }
  335. case cmPolicies::OLD:
  336. // OLD behavior is to do nothing.
  337. break;
  338. case cmPolicies::REQUIRED_IF_USED:
  339. case cmPolicies::REQUIRED_ALWAYS:
  340. this->Makefile->IssueMessage(
  341. cmake::FATAL_ERROR,
  342. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0056));
  343. case cmPolicies::NEW:
  344. // NEW behavior is to pass linker flags.
  345. {
  346. const char* exeLinkFlags =
  347. this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
  348. fprintf(
  349. fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
  350. cmOutputConverter::EscapeForCMake(exeLinkFlags ? exeLinkFlags : "")
  351. .c_str());
  352. }
  353. break;
  354. }
  355. fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
  356. " ${EXE_LINKER_FLAGS}\")\n");
  357. fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
  358. fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
  359. fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
  360. // handle any compile flags we need to pass on
  361. if (!compileDefs.empty()) {
  362. fprintf(fout, "add_definitions(%s)\n", cmJoin(compileDefs, " ").c_str());
  363. }
  364. /* Use a random file name to avoid rapid creation and deletion
  365. of the same executable name (some filesystems fail on that). */
  366. sprintf(targetNameBuf, "cmTC_%05x", cmSystemTools::RandomSeed() & 0xFFFFF);
  367. targetName = targetNameBuf;
  368. if (!targets.empty()) {
  369. std::string fname = "/" + std::string(targetName) + "Targets.cmake";
  370. cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile);
  371. tcfg.SetExportFile((this->BinaryDirectory + fname).c_str());
  372. tcfg.SetConfig(tcConfig);
  373. if (!tcfg.GenerateImportFile()) {
  374. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  375. "could not write export file.");
  376. fclose(fout);
  377. return -1;
  378. }
  379. fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  380. fname.c_str());
  381. }
  382. // Forward a set of variables to the inner project cache.
  383. {
  384. std::set<std::string> vars;
  385. vars.insert(kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN);
  386. vars.insert(kCMAKE_C_COMPILER_TARGET);
  387. vars.insert(kCMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN);
  388. vars.insert(kCMAKE_CXX_COMPILER_TARGET);
  389. vars.insert(kCMAKE_ENABLE_EXPORTS);
  390. vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
  391. vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
  392. vars.insert(kCMAKE_OSX_ARCHITECTURES);
  393. vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
  394. vars.insert(kCMAKE_OSX_SYSROOT);
  395. vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
  396. vars.insert(kCMAKE_SYSROOT);
  397. if (const char* varListStr = this->Makefile->GetDefinition(
  398. kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
  399. std::vector<std::string> varList;
  400. cmSystemTools::ExpandListArgument(varListStr, varList);
  401. vars.insert(varList.begin(), varList.end());
  402. }
  403. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  404. So the user can set CMAKE_OSX_ARCHITECTURES to i386;ppc and then set
  405. CMAKE_TRY_COMPILE_OSX_ARCHITECTURES first to i386 and then to ppc to
  406. have the tests run for each specific architecture. Since
  407. cmLocalGenerator doesn't allow building for "the other"
  408. architecture only via CMAKE_OSX_ARCHITECTURES.
  409. */
  410. if (const char* tcArchs = this->Makefile->GetDefinition(
  411. kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES)) {
  412. vars.erase(kCMAKE_OSX_ARCHITECTURES);
  413. std::string flag = "-DCMAKE_OSX_ARCHITECTURES=" + std::string(tcArchs);
  414. cmakeFlags.push_back(flag);
  415. }
  416. for (std::set<std::string>::iterator vi = vars.begin(); vi != vars.end();
  417. ++vi) {
  418. std::string const& var = *vi;
  419. if (const char* val = this->Makefile->GetDefinition(var)) {
  420. std::string flag = "-D" + var + "=" + val;
  421. cmakeFlags.push_back(flag);
  422. }
  423. }
  424. }
  425. /* Set the appropriate policy information for ENABLE_EXPORTS */
  426. fprintf(fout, "cmake_policy(SET CMP0065 %s)\n",
  427. this->Makefile->GetPolicyStatus(cmPolicies::CMP0065) ==
  428. cmPolicies::NEW
  429. ? "NEW"
  430. : "OLD");
  431. if (targetType == cmState::EXECUTABLE) {
  432. /* Put the executable at a known location (for COPY_FILE). */
  433. fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  434. this->BinaryDirectory.c_str());
  435. /* Create the actual executable. */
  436. fprintf(fout, "add_executable(%s", targetName.c_str());
  437. } else // if (targetType == cmState::STATIC_LIBRARY)
  438. {
  439. /* Put the static library at a known location (for COPY_FILE). */
  440. fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
  441. this->BinaryDirectory.c_str());
  442. /* Create the actual static library. */
  443. fprintf(fout, "add_library(%s STATIC", targetName.c_str());
  444. }
  445. for (std::vector<std::string>::iterator si = sources.begin();
  446. si != sources.end(); ++si) {
  447. fprintf(fout, " \"%s\"", si->c_str());
  448. // Add dependencies on any non-temporary sources.
  449. if (si->find("CMakeTmp") == si->npos) {
  450. this->Makefile->AddCMakeDependFile(*si);
  451. }
  452. }
  453. fprintf(fout, ")\n");
  454. if (useOldLinkLibs) {
  455. fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
  456. targetName.c_str());
  457. } else {
  458. fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
  459. libsToLink.c_str());
  460. }
  461. fclose(fout);
  462. projectName = "CMAKE_TRY_COMPILE";
  463. }
  464. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  465. cmSystemTools::ResetErrorOccuredFlag();
  466. std::string output;
  467. // actually do the try compile now that everything is setup
  468. int res = this->Makefile->TryCompile(
  469. sourceDirectory, this->BinaryDirectory, projectName, targetName,
  470. this->SrcFileSignature, &cmakeFlags, output);
  471. if (erroroc) {
  472. cmSystemTools::SetErrorOccured();
  473. }
  474. // set the result var to the return value to indicate success or failure
  475. this->Makefile->AddCacheDefinition(argv[0], (res == 0 ? "TRUE" : "FALSE"),
  476. "Result of TRY_COMPILE",
  477. cmState::INTERNAL);
  478. if (!outputVariable.empty()) {
  479. this->Makefile->AddDefinition(outputVariable, output.c_str());
  480. }
  481. if (this->SrcFileSignature) {
  482. std::string copyFileErrorMessage;
  483. this->FindOutputFile(targetName, targetType);
  484. if ((res == 0) && !copyFile.empty()) {
  485. if (this->OutputFile.empty() ||
  486. !cmSystemTools::CopyFileAlways(this->OutputFile, copyFile)) {
  487. std::ostringstream emsg;
  488. /* clang-format off */
  489. emsg << "Cannot copy output executable\n"
  490. << " '" << this->OutputFile << "'\n"
  491. << "to destination specified by COPY_FILE:\n"
  492. << " '" << copyFile << "'\n";
  493. /* clang-format on */
  494. if (!this->FindErrorMessage.empty()) {
  495. emsg << this->FindErrorMessage.c_str();
  496. }
  497. if (copyFileError.empty()) {
  498. this->Makefile->IssueMessage(cmake::FATAL_ERROR, emsg.str());
  499. return -1;
  500. } else {
  501. copyFileErrorMessage = emsg.str();
  502. }
  503. }
  504. }
  505. if (!copyFileError.empty()) {
  506. this->Makefile->AddDefinition(copyFileError,
  507. copyFileErrorMessage.c_str());
  508. }
  509. }
  510. return res;
  511. }
  512. void cmCoreTryCompile::CleanupFiles(const char* binDir)
  513. {
  514. if (!binDir) {
  515. return;
  516. }
  517. std::string bdir = binDir;
  518. if (bdir.find("CMakeTmp") == std::string::npos) {
  519. cmSystemTools::Error(
  520. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  521. "CMakeTmp:",
  522. binDir);
  523. return;
  524. }
  525. cmsys::Directory dir;
  526. dir.Load(binDir);
  527. size_t fileNum;
  528. std::set<std::string> deletedFiles;
  529. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
  530. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
  531. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
  532. if (deletedFiles.find(dir.GetFile(
  533. static_cast<unsigned long>(fileNum))) == deletedFiles.end()) {
  534. deletedFiles.insert(dir.GetFile(static_cast<unsigned long>(fileNum)));
  535. std::string fullPath = binDir;
  536. fullPath += "/";
  537. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  538. if (cmSystemTools::FileIsDirectory(fullPath)) {
  539. this->CleanupFiles(fullPath.c_str());
  540. cmSystemTools::RemoveADirectory(fullPath);
  541. } else {
  542. #ifdef _WIN32
  543. // Sometimes anti-virus software hangs on to new files so we
  544. // cannot delete them immediately. Try a few times.
  545. cmSystemTools::WindowsFileRetry retry =
  546. cmSystemTools::GetWindowsFileRetry();
  547. while (!cmSystemTools::RemoveFile(fullPath.c_str()) &&
  548. --retry.Count &&
  549. cmSystemTools::FileExists(fullPath.c_str())) {
  550. cmSystemTools::Delay(retry.Delay);
  551. }
  552. if (retry.Count == 0)
  553. #else
  554. if (!cmSystemTools::RemoveFile(fullPath))
  555. #endif
  556. {
  557. std::string m = "Remove failed on file: " + fullPath;
  558. cmSystemTools::ReportLastSystemError(m.c_str());
  559. }
  560. }
  561. }
  562. }
  563. }
  564. }
  565. void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
  566. cmState::TargetType targetType)
  567. {
  568. this->FindErrorMessage = "";
  569. this->OutputFile = "";
  570. std::string tmpOutputFile = "/";
  571. if (targetType == cmState::EXECUTABLE) {
  572. tmpOutputFile += targetName;
  573. tmpOutputFile +=
  574. this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  575. } else // if (targetType == cmState::STATIC_LIBRARY)
  576. {
  577. tmpOutputFile +=
  578. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX");
  579. tmpOutputFile += targetName;
  580. tmpOutputFile +=
  581. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX");
  582. }
  583. // a list of directories where to search for the compilation result
  584. // at first directly in the binary dir
  585. std::vector<std::string> searchDirs;
  586. searchDirs.push_back("");
  587. const char* config =
  588. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  589. // if a config was specified try that first
  590. if (config && config[0]) {
  591. std::string tmp = "/";
  592. tmp += config;
  593. searchDirs.push_back(tmp);
  594. }
  595. searchDirs.push_back("/Debug");
  596. #if defined(__APPLE__)
  597. std::string app = "/Debug/" + targetName + ".app";
  598. searchDirs.push_back(app);
  599. #endif
  600. searchDirs.push_back("/Development");
  601. for (std::vector<std::string>::const_iterator it = searchDirs.begin();
  602. it != searchDirs.end(); ++it) {
  603. std::string command = this->BinaryDirectory;
  604. command += *it;
  605. command += tmpOutputFile;
  606. if (cmSystemTools::FileExists(command.c_str())) {
  607. this->OutputFile = cmSystemTools::CollapseFullPath(command);
  608. return;
  609. }
  610. }
  611. std::ostringstream emsg;
  612. emsg << "Unable to find the executable at any of:\n";
  613. emsg << cmWrap(" " + this->BinaryDirectory, searchDirs, tmpOutputFile, "\n")
  614. << "\n";
  615. this->FindErrorMessage = emsg.str();
  616. return;
  617. }