cmCoreTryCompile.cxx 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCoreTryCompile.h"
  4. #include "cmsys/Directory.hxx"
  5. #include <set>
  6. #include <sstream>
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <utility>
  10. #include "cmAlgorithms.h"
  11. #include "cmExportTryCompileFileGenerator.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmOutputConverter.h"
  15. #include "cmPolicies.h"
  16. #include "cmState.h"
  17. #include "cmSystemTools.h"
  18. #include "cmTarget.h"
  19. #include "cmVersion.h"
  20. #include "cmake.h"
  21. static std::string const kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN =
  22. "CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN";
  23. static std::string const kCMAKE_C_COMPILER_TARGET = "CMAKE_C_COMPILER_TARGET";
  24. static std::string const kCMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN =
  25. "CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN";
  26. static std::string const kCMAKE_CXX_COMPILER_TARGET =
  27. "CMAKE_CXX_COMPILER_TARGET";
  28. static std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
  29. static std::string const kCMAKE_LINK_SEARCH_END_STATIC =
  30. "CMAKE_LINK_SEARCH_END_STATIC";
  31. static std::string const kCMAKE_LINK_SEARCH_START_STATIC =
  32. "CMAKE_LINK_SEARCH_START_STATIC";
  33. static std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
  34. static std::string const kCMAKE_OSX_DEPLOYMENT_TARGET =
  35. "CMAKE_OSX_DEPLOYMENT_TARGET";
  36. static std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
  37. static std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
  38. "CMAKE_POSITION_INDEPENDENT_CODE";
  39. static std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
  40. static std::string const kCMAKE_SYSROOT_COMPILE = "CMAKE_SYSROOT_COMPILE";
  41. static std::string const kCMAKE_SYSROOT_LINK = "CMAKE_SYSROOT_LINK";
  42. static std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
  43. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
  44. static std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
  45. "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
  46. static std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
  47. static void writeProperty(FILE* fout, std::string const& targetName,
  48. std::string const& prop, std::string const& value)
  49. {
  50. fprintf(fout, "set_property(TARGET %s PROPERTY %s %s)\n", targetName.c_str(),
  51. cmOutputConverter::EscapeForCMake(prop).c_str(),
  52. cmOutputConverter::EscapeForCMake(value).c_str());
  53. }
  54. std::string cmCoreTryCompile::LookupStdVar(std::string const& var,
  55. bool warnCMP0067)
  56. {
  57. std::string value = this->Makefile->GetSafeDefinition(var);
  58. if (warnCMP0067 && !value.empty()) {
  59. value.clear();
  60. this->WarnCMP0067.push_back(var);
  61. }
  62. return value;
  63. }
  64. int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
  65. bool isTryRun)
  66. {
  67. this->BinaryDirectory = argv[1];
  68. this->OutputFile.clear();
  69. // which signature were we called with ?
  70. this->SrcFileSignature = true;
  71. cmStateEnums::TargetType targetType = cmStateEnums::EXECUTABLE;
  72. const char* tt =
  73. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_TARGET_TYPE");
  74. if (!isTryRun && tt && *tt) {
  75. if (strcmp(tt, cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE)) ==
  76. 0) {
  77. targetType = cmStateEnums::EXECUTABLE;
  78. } else if (strcmp(tt, cmState::GetTargetTypeName(
  79. cmStateEnums::STATIC_LIBRARY)) == 0) {
  80. targetType = cmStateEnums::STATIC_LIBRARY;
  81. } else {
  82. this->Makefile->IssueMessage(
  83. cmake::FATAL_ERROR, std::string("Invalid value '") + tt +
  84. "' for "
  85. "CMAKE_TRY_COMPILE_TARGET_TYPE. Only "
  86. "'" +
  87. cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE) + "' and "
  88. "'" +
  89. cmState::GetTargetTypeName(cmStateEnums::STATIC_LIBRARY) +
  90. "' "
  91. "are allowed.");
  92. return -1;
  93. }
  94. }
  95. const char* sourceDirectory = argv[2].c_str();
  96. const char* projectName = nullptr;
  97. std::string targetName;
  98. std::vector<std::string> cmakeFlags(1, "CMAKE_FLAGS"); // fake argv[0]
  99. std::vector<std::string> compileDefs;
  100. std::string outputVariable;
  101. std::string copyFile;
  102. std::string copyFileError;
  103. std::string cStandard;
  104. std::string cxxStandard;
  105. std::string cudaStandard;
  106. std::string cStandardRequired;
  107. std::string cxxStandardRequired;
  108. std::string cudaStandardRequired;
  109. std::string cExtensions;
  110. std::string cxxExtensions;
  111. std::string cudaExtensions;
  112. std::vector<std::string> targets;
  113. std::string libsToLink = " ";
  114. bool useOldLinkLibs = true;
  115. char targetNameBuf[64];
  116. bool didOutputVariable = false;
  117. bool didCopyFile = false;
  118. bool didCopyFileError = false;
  119. bool didCStandard = false;
  120. bool didCxxStandard = false;
  121. bool didCudaStandard = false;
  122. bool didCStandardRequired = false;
  123. bool didCxxStandardRequired = false;
  124. bool didCudaStandardRequired = false;
  125. bool didCExtensions = false;
  126. bool didCxxExtensions = false;
  127. bool didCudaExtensions = false;
  128. bool useSources = argv[2] == "SOURCES";
  129. std::vector<std::string> sources;
  130. enum Doing
  131. {
  132. DoingNone,
  133. DoingCMakeFlags,
  134. DoingCompileDefinitions,
  135. DoingLinkLibraries,
  136. DoingOutputVariable,
  137. DoingCopyFile,
  138. DoingCopyFileError,
  139. DoingCStandard,
  140. DoingCxxStandard,
  141. DoingCudaStandard,
  142. DoingCStandardRequired,
  143. DoingCxxStandardRequired,
  144. DoingCudaStandardRequired,
  145. DoingCExtensions,
  146. DoingCxxExtensions,
  147. DoingCudaExtensions,
  148. DoingSources
  149. };
  150. Doing doing = useSources ? DoingSources : DoingNone;
  151. for (size_t i = 3; i < argv.size(); ++i) {
  152. if (argv[i] == "CMAKE_FLAGS") {
  153. doing = DoingCMakeFlags;
  154. } else if (argv[i] == "COMPILE_DEFINITIONS") {
  155. doing = DoingCompileDefinitions;
  156. } else if (argv[i] == "LINK_LIBRARIES") {
  157. doing = DoingLinkLibraries;
  158. useOldLinkLibs = false;
  159. } else if (argv[i] == "OUTPUT_VARIABLE") {
  160. doing = DoingOutputVariable;
  161. didOutputVariable = true;
  162. } else if (argv[i] == "COPY_FILE") {
  163. doing = DoingCopyFile;
  164. didCopyFile = true;
  165. } else if (argv[i] == "COPY_FILE_ERROR") {
  166. doing = DoingCopyFileError;
  167. didCopyFileError = true;
  168. } else if (argv[i] == "C_STANDARD") {
  169. doing = DoingCStandard;
  170. didCStandard = true;
  171. } else if (argv[i] == "CXX_STANDARD") {
  172. doing = DoingCxxStandard;
  173. didCxxStandard = true;
  174. } else if (argv[i] == "CUDA_STANDARD") {
  175. doing = DoingCudaStandard;
  176. didCudaStandard = true;
  177. } else if (argv[i] == "C_STANDARD_REQUIRED") {
  178. doing = DoingCStandardRequired;
  179. didCStandardRequired = true;
  180. } else if (argv[i] == "CXX_STANDARD_REQUIRED") {
  181. doing = DoingCxxStandardRequired;
  182. didCxxStandardRequired = true;
  183. } else if (argv[i] == "CUDA_STANDARD_REQUIRED") {
  184. doing = DoingCudaStandardRequired;
  185. didCudaStandardRequired = true;
  186. } else if (argv[i] == "C_EXTENSIONS") {
  187. doing = DoingCExtensions;
  188. didCExtensions = true;
  189. } else if (argv[i] == "CXX_EXTENSIONS") {
  190. doing = DoingCxxExtensions;
  191. didCxxExtensions = true;
  192. } else if (argv[i] == "CUDA_EXTENSIONS") {
  193. doing = DoingCudaExtensions;
  194. didCudaExtensions = true;
  195. } else if (doing == DoingCMakeFlags) {
  196. cmakeFlags.push_back(argv[i]);
  197. } else if (doing == DoingCompileDefinitions) {
  198. compileDefs.push_back(argv[i]);
  199. } else if (doing == DoingLinkLibraries) {
  200. libsToLink += "\"" + cmSystemTools::TrimWhitespace(argv[i]) + "\" ";
  201. if (cmTarget* tgt = this->Makefile->FindTargetToUse(argv[i])) {
  202. switch (tgt->GetType()) {
  203. case cmStateEnums::SHARED_LIBRARY:
  204. case cmStateEnums::STATIC_LIBRARY:
  205. case cmStateEnums::INTERFACE_LIBRARY:
  206. case cmStateEnums::UNKNOWN_LIBRARY:
  207. break;
  208. case cmStateEnums::EXECUTABLE:
  209. if (tgt->IsExecutableWithExports()) {
  210. break;
  211. }
  212. CM_FALLTHROUGH;
  213. default:
  214. this->Makefile->IssueMessage(
  215. cmake::FATAL_ERROR,
  216. "Only libraries may be used as try_compile or try_run IMPORTED "
  217. "LINK_LIBRARIES. Got " +
  218. std::string(tgt->GetName()) + " of "
  219. "type " +
  220. cmState::GetTargetTypeName(tgt->GetType()) + ".");
  221. return -1;
  222. }
  223. if (tgt->IsImported()) {
  224. targets.push_back(argv[i]);
  225. }
  226. }
  227. } else if (doing == DoingOutputVariable) {
  228. outputVariable = argv[i];
  229. doing = DoingNone;
  230. } else if (doing == DoingCopyFile) {
  231. copyFile = argv[i];
  232. doing = DoingNone;
  233. } else if (doing == DoingCopyFileError) {
  234. copyFileError = argv[i];
  235. doing = DoingNone;
  236. } else if (doing == DoingCStandard) {
  237. cStandard = argv[i];
  238. doing = DoingNone;
  239. } else if (doing == DoingCxxStandard) {
  240. cxxStandard = argv[i];
  241. doing = DoingNone;
  242. } else if (doing == DoingCudaStandard) {
  243. cudaStandard = argv[i];
  244. doing = DoingNone;
  245. } else if (doing == DoingCStandardRequired) {
  246. cStandardRequired = argv[i];
  247. doing = DoingNone;
  248. } else if (doing == DoingCxxStandardRequired) {
  249. cxxStandardRequired = argv[i];
  250. doing = DoingNone;
  251. } else if (doing == DoingCudaStandardRequired) {
  252. cudaStandardRequired = argv[i];
  253. doing = DoingNone;
  254. } else if (doing == DoingCExtensions) {
  255. cExtensions = argv[i];
  256. doing = DoingNone;
  257. } else if (doing == DoingCxxExtensions) {
  258. cxxExtensions = argv[i];
  259. doing = DoingNone;
  260. } else if (doing == DoingCudaExtensions) {
  261. cudaExtensions = argv[i];
  262. doing = DoingNone;
  263. } else if (doing == DoingSources) {
  264. sources.push_back(argv[i]);
  265. } else if (i == 3) {
  266. this->SrcFileSignature = false;
  267. projectName = argv[i].c_str();
  268. } else if (i == 4 && !this->SrcFileSignature) {
  269. targetName = argv[i];
  270. } else {
  271. std::ostringstream m;
  272. m << "try_compile given unknown argument \"" << argv[i] << "\".";
  273. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, m.str());
  274. }
  275. }
  276. if (didCopyFile && copyFile.empty()) {
  277. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  278. "COPY_FILE must be followed by a file path");
  279. return -1;
  280. }
  281. if (didCopyFileError && copyFileError.empty()) {
  282. this->Makefile->IssueMessage(
  283. cmake::FATAL_ERROR,
  284. "COPY_FILE_ERROR must be followed by a variable name");
  285. return -1;
  286. }
  287. if (didCopyFileError && !didCopyFile) {
  288. this->Makefile->IssueMessage(
  289. cmake::FATAL_ERROR, "COPY_FILE_ERROR may be used only with COPY_FILE");
  290. return -1;
  291. }
  292. if (didOutputVariable && outputVariable.empty()) {
  293. this->Makefile->IssueMessage(
  294. cmake::FATAL_ERROR,
  295. "OUTPUT_VARIABLE must be followed by a variable name");
  296. return -1;
  297. }
  298. if (useSources && sources.empty()) {
  299. this->Makefile->IssueMessage(
  300. cmake::FATAL_ERROR,
  301. "SOURCES must be followed by at least one source file");
  302. return -1;
  303. }
  304. if (didCStandard && !this->SrcFileSignature) {
  305. this->Makefile->IssueMessage(
  306. cmake::FATAL_ERROR, "C_STANDARD allowed only in source file signature.");
  307. return -1;
  308. }
  309. if (didCxxStandard && !this->SrcFileSignature) {
  310. this->Makefile->IssueMessage(
  311. cmake::FATAL_ERROR,
  312. "CXX_STANDARD allowed only in source file signature.");
  313. return -1;
  314. }
  315. if (didCudaStandard && !this->SrcFileSignature) {
  316. this->Makefile->IssueMessage(
  317. cmake::FATAL_ERROR,
  318. "CUDA_STANDARD allowed only in source file signature.");
  319. return -1;
  320. }
  321. if (didCStandardRequired && !this->SrcFileSignature) {
  322. this->Makefile->IssueMessage(
  323. cmake::FATAL_ERROR,
  324. "C_STANDARD_REQUIRED allowed only in source file signature.");
  325. return -1;
  326. }
  327. if (didCxxStandardRequired && !this->SrcFileSignature) {
  328. this->Makefile->IssueMessage(
  329. cmake::FATAL_ERROR,
  330. "CXX_STANDARD_REQUIRED allowed only in source file signature.");
  331. return -1;
  332. }
  333. if (didCudaStandardRequired && !this->SrcFileSignature) {
  334. this->Makefile->IssueMessage(
  335. cmake::FATAL_ERROR,
  336. "CUDA_STANDARD_REQUIRED allowed only in source file signature.");
  337. return -1;
  338. }
  339. if (didCExtensions && !this->SrcFileSignature) {
  340. this->Makefile->IssueMessage(
  341. cmake::FATAL_ERROR,
  342. "C_EXTENSIONS allowed only in source file signature.");
  343. return -1;
  344. }
  345. if (didCxxExtensions && !this->SrcFileSignature) {
  346. this->Makefile->IssueMessage(
  347. cmake::FATAL_ERROR,
  348. "CXX_EXTENSIONS allowed only in source file signature.");
  349. return -1;
  350. }
  351. if (didCudaExtensions && !this->SrcFileSignature) {
  352. this->Makefile->IssueMessage(
  353. cmake::FATAL_ERROR,
  354. "CUDA_EXTENSIONS allowed only in source file signature.");
  355. return -1;
  356. }
  357. // compute the binary dir when TRY_COMPILE is called with a src file
  358. // signature
  359. if (this->SrcFileSignature) {
  360. this->BinaryDirectory += cmake::GetCMakeFilesDirectory();
  361. this->BinaryDirectory += "/CMakeTmp";
  362. } else {
  363. // only valid for srcfile signatures
  364. if (!compileDefs.empty()) {
  365. this->Makefile->IssueMessage(
  366. cmake::FATAL_ERROR,
  367. "COMPILE_DEFINITIONS specified on a srcdir type TRY_COMPILE");
  368. return -1;
  369. }
  370. if (!copyFile.empty()) {
  371. this->Makefile->IssueMessage(
  372. cmake::FATAL_ERROR,
  373. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  374. return -1;
  375. }
  376. }
  377. // make sure the binary directory exists
  378. cmSystemTools::MakeDirectory(this->BinaryDirectory);
  379. // do not allow recursive try Compiles
  380. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
  381. std::ostringstream e;
  382. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  383. << " " << this->BinaryDirectory << "\n";
  384. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  385. return -1;
  386. }
  387. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  388. // which signature are we using? If we are using var srcfile bindir
  389. if (this->SrcFileSignature) {
  390. // remove any CMakeCache.txt files so we will have a clean test
  391. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  392. cmSystemTools::RemoveFile(ccFile);
  393. // Choose sources.
  394. if (!useSources) {
  395. sources.push_back(argv[2]);
  396. }
  397. // Detect languages to enable.
  398. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  399. std::set<std::string> testLangs;
  400. for (std::string const& si : sources) {
  401. std::string ext = cmSystemTools::GetFilenameLastExtension(si);
  402. std::string lang = gg->GetLanguageFromExtension(ext.c_str());
  403. if (!lang.empty()) {
  404. testLangs.insert(lang);
  405. } else {
  406. std::ostringstream err;
  407. err << "Unknown extension \"" << ext << "\" for file\n"
  408. << " " << si << "\n"
  409. << "try_compile() works only for enabled languages. "
  410. << "Currently these are:\n ";
  411. std::vector<std::string> langs;
  412. gg->GetEnabledLanguages(langs);
  413. err << cmJoin(langs, " ");
  414. err << "\nSee project() command to enable other languages.";
  415. this->Makefile->IssueMessage(cmake::FATAL_ERROR, err.str());
  416. return -1;
  417. }
  418. }
  419. std::string const tcConfig =
  420. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  421. // we need to create a directory and CMakeLists file etc...
  422. // first create the directories
  423. sourceDirectory = this->BinaryDirectory.c_str();
  424. // now create a CMakeLists.txt file in that directory
  425. FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
  426. if (!fout) {
  427. std::ostringstream e;
  428. /* clang-format off */
  429. e << "Failed to open\n"
  430. << " " << outFileName << "\n"
  431. << cmSystemTools::GetLastSystemError();
  432. /* clang-format on */
  433. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  434. return -1;
  435. }
  436. const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  437. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  438. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  439. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  440. if (def) {
  441. fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def);
  442. }
  443. std::string projectLangs;
  444. for (std::string const& li : testLangs) {
  445. projectLangs += " " + li;
  446. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  447. std::string rulesOverrideLang = rulesOverrideBase + "_" + li;
  448. if (const char* rulesOverridePath =
  449. this->Makefile->GetDefinition(rulesOverrideLang)) {
  450. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
  451. rulesOverridePath);
  452. } else if (const char* rulesOverridePath2 =
  453. this->Makefile->GetDefinition(rulesOverrideBase)) {
  454. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
  455. rulesOverridePath2);
  456. }
  457. }
  458. fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  459. fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
  460. for (std::string const& li : testLangs) {
  461. std::string langFlags = "CMAKE_" + li + "_FLAGS";
  462. const char* flags = this->Makefile->GetDefinition(langFlags);
  463. fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
  464. cmOutputConverter::EscapeForCMake(flags ? flags : "").c_str());
  465. fprintf(fout, "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
  466. " ${COMPILE_DEFINITIONS}\")\n",
  467. li.c_str(), li.c_str());
  468. }
  469. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
  470. case cmPolicies::WARN:
  471. if (this->Makefile->PolicyOptionalWarningEnabled(
  472. "CMAKE_POLICY_WARNING_CMP0066")) {
  473. std::ostringstream w;
  474. /* clang-format off */
  475. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
  476. "For compatibility with older versions of CMake, try_compile "
  477. "is not honoring caller config-specific compiler flags "
  478. "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
  479. ;
  480. /* clang-format on */
  481. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  482. }
  483. case cmPolicies::OLD:
  484. // OLD behavior is to do nothing.
  485. break;
  486. case cmPolicies::REQUIRED_IF_USED:
  487. case cmPolicies::REQUIRED_ALWAYS:
  488. this->Makefile->IssueMessage(
  489. cmake::FATAL_ERROR,
  490. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0066));
  491. CM_FALLTHROUGH;
  492. case cmPolicies::NEW: {
  493. // NEW behavior is to pass config-specific compiler flags.
  494. static std::string const cfgDefault = "DEBUG";
  495. std::string const cfg =
  496. !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
  497. for (std::string const& li : testLangs) {
  498. std::string const langFlagsCfg = "CMAKE_" + li + "_FLAGS_" + cfg;
  499. const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
  500. fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
  501. cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "")
  502. .c_str());
  503. }
  504. } break;
  505. }
  506. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
  507. case cmPolicies::WARN:
  508. if (this->Makefile->PolicyOptionalWarningEnabled(
  509. "CMAKE_POLICY_WARNING_CMP0056")) {
  510. std::ostringstream w;
  511. /* clang-format off */
  512. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0056) << "\n"
  513. "For compatibility with older versions of CMake, try_compile "
  514. "is not honoring caller link flags (e.g. CMAKE_EXE_LINKER_FLAGS) "
  515. "in the test project."
  516. ;
  517. /* clang-format on */
  518. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  519. }
  520. case cmPolicies::OLD:
  521. // OLD behavior is to do nothing.
  522. break;
  523. case cmPolicies::REQUIRED_IF_USED:
  524. case cmPolicies::REQUIRED_ALWAYS:
  525. this->Makefile->IssueMessage(
  526. cmake::FATAL_ERROR,
  527. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0056));
  528. CM_FALLTHROUGH;
  529. case cmPolicies::NEW:
  530. // NEW behavior is to pass linker flags.
  531. {
  532. const char* exeLinkFlags =
  533. this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
  534. fprintf(
  535. fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
  536. cmOutputConverter::EscapeForCMake(exeLinkFlags ? exeLinkFlags : "")
  537. .c_str());
  538. }
  539. break;
  540. }
  541. fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
  542. " ${EXE_LINKER_FLAGS}\")\n");
  543. fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
  544. fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
  545. fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
  546. // handle any compile flags we need to pass on
  547. if (!compileDefs.empty()) {
  548. fprintf(fout, "add_definitions(%s)\n", cmJoin(compileDefs, " ").c_str());
  549. }
  550. /* Use a random file name to avoid rapid creation and deletion
  551. of the same executable name (some filesystems fail on that). */
  552. sprintf(targetNameBuf, "cmTC_%05x", cmSystemTools::RandomSeed() & 0xFFFFF);
  553. targetName = targetNameBuf;
  554. if (!targets.empty()) {
  555. std::string fname = "/" + std::string(targetName) + "Targets.cmake";
  556. cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile,
  557. testLangs);
  558. tcfg.SetExportFile((this->BinaryDirectory + fname).c_str());
  559. tcfg.SetConfig(tcConfig);
  560. if (!tcfg.GenerateImportFile()) {
  561. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  562. "could not write export file.");
  563. fclose(fout);
  564. return -1;
  565. }
  566. fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  567. fname.c_str());
  568. }
  569. // Forward a set of variables to the inner project cache.
  570. {
  571. std::set<std::string> vars;
  572. vars.insert(kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN);
  573. vars.insert(kCMAKE_C_COMPILER_TARGET);
  574. vars.insert(kCMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN);
  575. vars.insert(kCMAKE_CXX_COMPILER_TARGET);
  576. vars.insert(kCMAKE_ENABLE_EXPORTS);
  577. vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
  578. vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
  579. vars.insert(kCMAKE_OSX_ARCHITECTURES);
  580. vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
  581. vars.insert(kCMAKE_OSX_SYSROOT);
  582. vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
  583. vars.insert(kCMAKE_SYSROOT);
  584. vars.insert(kCMAKE_SYSROOT_COMPILE);
  585. vars.insert(kCMAKE_SYSROOT_LINK);
  586. vars.insert(kCMAKE_WARN_DEPRECATED);
  587. if (const char* varListStr = this->Makefile->GetDefinition(
  588. kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
  589. std::vector<std::string> varList;
  590. cmSystemTools::ExpandListArgument(varListStr, varList);
  591. vars.insert(varList.begin(), varList.end());
  592. }
  593. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  594. So the user can set CMAKE_OSX_ARCHITECTURES to i386;ppc and then set
  595. CMAKE_TRY_COMPILE_OSX_ARCHITECTURES first to i386 and then to ppc to
  596. have the tests run for each specific architecture. Since
  597. cmLocalGenerator doesn't allow building for "the other"
  598. architecture only via CMAKE_OSX_ARCHITECTURES.
  599. */
  600. if (const char* tcArchs = this->Makefile->GetDefinition(
  601. kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES)) {
  602. vars.erase(kCMAKE_OSX_ARCHITECTURES);
  603. std::string flag = "-DCMAKE_OSX_ARCHITECTURES=" + std::string(tcArchs);
  604. cmakeFlags.push_back(std::move(flag));
  605. }
  606. for (std::string const& var : vars) {
  607. if (const char* val = this->Makefile->GetDefinition(var)) {
  608. std::string flag = "-D" + var + "=" + val;
  609. cmakeFlags.push_back(std::move(flag));
  610. }
  611. }
  612. }
  613. /* Set the appropriate policy information for ENABLE_EXPORTS */
  614. fprintf(fout, "cmake_policy(SET CMP0065 %s)\n",
  615. this->Makefile->GetPolicyStatus(cmPolicies::CMP0065) ==
  616. cmPolicies::NEW
  617. ? "NEW"
  618. : "OLD");
  619. if (targetType == cmStateEnums::EXECUTABLE) {
  620. /* Put the executable at a known location (for COPY_FILE). */
  621. fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  622. this->BinaryDirectory.c_str());
  623. /* Create the actual executable. */
  624. fprintf(fout, "add_executable(%s", targetName.c_str());
  625. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  626. {
  627. /* Put the static library at a known location (for COPY_FILE). */
  628. fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
  629. this->BinaryDirectory.c_str());
  630. /* Create the actual static library. */
  631. fprintf(fout, "add_library(%s STATIC", targetName.c_str());
  632. }
  633. for (std::string const& si : sources) {
  634. fprintf(fout, " \"%s\"", si.c_str());
  635. // Add dependencies on any non-temporary sources.
  636. if (si.find("CMakeTmp") == std::string::npos) {
  637. this->Makefile->AddCMakeDependFile(si);
  638. }
  639. }
  640. fprintf(fout, ")\n");
  641. bool const testC = testLangs.find("C") != testLangs.end();
  642. bool const testCxx = testLangs.find("CXX") != testLangs.end();
  643. bool const testCuda = testLangs.find("CUDA") != testLangs.end();
  644. bool warnCMP0067 = false;
  645. bool honorStandard = true;
  646. if (!didCStandard && !didCxxStandard && !didCudaStandard &&
  647. !didCStandardRequired && !didCxxStandardRequired &&
  648. !didCudaStandardRequired && !didCExtensions && !didCxxExtensions &&
  649. !didCudaExtensions) {
  650. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0067)) {
  651. case cmPolicies::WARN:
  652. warnCMP0067 = this->Makefile->PolicyOptionalWarningEnabled(
  653. "CMAKE_POLICY_WARNING_CMP0067");
  654. CM_FALLTHROUGH;
  655. case cmPolicies::OLD:
  656. // OLD behavior is to not honor the language standard variables.
  657. honorStandard = false;
  658. break;
  659. case cmPolicies::REQUIRED_IF_USED:
  660. case cmPolicies::REQUIRED_ALWAYS:
  661. this->Makefile->IssueMessage(
  662. cmake::FATAL_ERROR,
  663. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0067));
  664. case cmPolicies::NEW:
  665. // NEW behavior is to honor the language standard variables.
  666. // We already initialized honorStandard to true.
  667. break;
  668. }
  669. }
  670. if (honorStandard || warnCMP0067) {
  671. if (testC) {
  672. if (!didCStandard) {
  673. cStandard = this->LookupStdVar("CMAKE_C_STANDARD", warnCMP0067);
  674. }
  675. if (!didCStandardRequired) {
  676. cStandardRequired =
  677. this->LookupStdVar("CMAKE_C_STANDARD_REQUIRED", warnCMP0067);
  678. }
  679. if (!didCExtensions) {
  680. cExtensions = this->LookupStdVar("CMAKE_C_EXTENSIONS", warnCMP0067);
  681. }
  682. }
  683. if (testCxx) {
  684. if (!didCxxStandard) {
  685. cxxStandard = this->LookupStdVar("CMAKE_CXX_STANDARD", warnCMP0067);
  686. }
  687. if (!didCxxStandardRequired) {
  688. cxxStandardRequired =
  689. this->LookupStdVar("CMAKE_CXX_STANDARD_REQUIRED", warnCMP0067);
  690. }
  691. if (!didCxxExtensions) {
  692. cxxExtensions =
  693. this->LookupStdVar("CMAKE_CXX_EXTENSIONS", warnCMP0067);
  694. }
  695. }
  696. if (testCuda) {
  697. if (!didCudaStandard) {
  698. cudaStandard =
  699. this->LookupStdVar("CMAKE_CUDA_STANDARD", warnCMP0067);
  700. }
  701. if (!didCudaStandardRequired) {
  702. cudaStandardRequired =
  703. this->LookupStdVar("CMAKE_CUDA_STANDARD_REQUIRED", warnCMP0067);
  704. }
  705. if (!didCudaExtensions) {
  706. cudaExtensions =
  707. this->LookupStdVar("CMAKE_CUDA_EXTENSIONS", warnCMP0067);
  708. }
  709. }
  710. }
  711. if (!this->WarnCMP0067.empty()) {
  712. std::ostringstream w;
  713. /* clang-format off */
  714. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0067) << "\n"
  715. "For compatibility with older versions of CMake, try_compile "
  716. "is not honoring language standard variables in the test project:\n"
  717. ;
  718. /* clang-format on */
  719. for (std::string const& vi : this->WarnCMP0067) {
  720. w << " " << vi << "\n";
  721. }
  722. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  723. }
  724. if (testC) {
  725. if (!cStandard.empty()) {
  726. writeProperty(fout, targetName, "C_STANDARD", cStandard);
  727. }
  728. if (!cStandardRequired.empty()) {
  729. writeProperty(fout, targetName, "C_STANDARD_REQUIRED",
  730. cStandardRequired);
  731. }
  732. if (!cExtensions.empty()) {
  733. writeProperty(fout, targetName, "C_EXTENSIONS", cExtensions);
  734. }
  735. }
  736. if (testCxx) {
  737. if (!cxxStandard.empty()) {
  738. writeProperty(fout, targetName, "CXX_STANDARD", cxxStandard);
  739. }
  740. if (!cxxStandardRequired.empty()) {
  741. writeProperty(fout, targetName, "CXX_STANDARD_REQUIRED",
  742. cxxStandardRequired);
  743. }
  744. if (!cxxExtensions.empty()) {
  745. writeProperty(fout, targetName, "CXX_EXTENSIONS", cxxExtensions);
  746. }
  747. }
  748. if (testCuda) {
  749. if (!cudaStandard.empty()) {
  750. writeProperty(fout, targetName, "CUDA_STANDARD", cudaStandard);
  751. }
  752. if (!cudaStandardRequired.empty()) {
  753. writeProperty(fout, targetName, "CUDA_STANDARD_REQUIRED",
  754. cudaStandardRequired);
  755. }
  756. if (!cudaExtensions.empty()) {
  757. writeProperty(fout, targetName, "CUDA_EXTENSIONS", cudaExtensions);
  758. }
  759. }
  760. if (useOldLinkLibs) {
  761. fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
  762. targetName.c_str());
  763. } else {
  764. fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
  765. libsToLink.c_str());
  766. }
  767. fclose(fout);
  768. projectName = "CMAKE_TRY_COMPILE";
  769. }
  770. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  771. cmSystemTools::ResetErrorOccuredFlag();
  772. std::string output;
  773. // actually do the try compile now that everything is setup
  774. int res = this->Makefile->TryCompile(
  775. sourceDirectory, this->BinaryDirectory, projectName, targetName,
  776. this->SrcFileSignature, &cmakeFlags, output);
  777. if (erroroc) {
  778. cmSystemTools::SetErrorOccured();
  779. }
  780. // set the result var to the return value to indicate success or failure
  781. this->Makefile->AddCacheDefinition(argv[0], (res == 0 ? "TRUE" : "FALSE"),
  782. "Result of TRY_COMPILE",
  783. cmStateEnums::INTERNAL);
  784. if (!outputVariable.empty()) {
  785. this->Makefile->AddDefinition(outputVariable, output.c_str());
  786. }
  787. if (this->SrcFileSignature) {
  788. std::string copyFileErrorMessage;
  789. this->FindOutputFile(targetName, targetType);
  790. if ((res == 0) && !copyFile.empty()) {
  791. if (this->OutputFile.empty() ||
  792. !cmSystemTools::CopyFileAlways(this->OutputFile, copyFile)) {
  793. std::ostringstream emsg;
  794. /* clang-format off */
  795. emsg << "Cannot copy output executable\n"
  796. << " '" << this->OutputFile << "'\n"
  797. << "to destination specified by COPY_FILE:\n"
  798. << " '" << copyFile << "'\n";
  799. /* clang-format on */
  800. if (!this->FindErrorMessage.empty()) {
  801. emsg << this->FindErrorMessage.c_str();
  802. }
  803. if (copyFileError.empty()) {
  804. this->Makefile->IssueMessage(cmake::FATAL_ERROR, emsg.str());
  805. return -1;
  806. }
  807. copyFileErrorMessage = emsg.str();
  808. }
  809. }
  810. if (!copyFileError.empty()) {
  811. this->Makefile->AddDefinition(copyFileError,
  812. copyFileErrorMessage.c_str());
  813. }
  814. }
  815. return res;
  816. }
  817. void cmCoreTryCompile::CleanupFiles(std::string const& binDir)
  818. {
  819. if (binDir.empty()) {
  820. return;
  821. }
  822. if (binDir.find("CMakeTmp") == std::string::npos) {
  823. cmSystemTools::Error(
  824. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  825. "CMakeTmp:",
  826. binDir.c_str());
  827. return;
  828. }
  829. cmsys::Directory dir;
  830. dir.Load(binDir);
  831. std::set<std::string> deletedFiles;
  832. for (unsigned long i = 0; i < dir.GetNumberOfFiles(); ++i) {
  833. const char* fileName = dir.GetFile(i);
  834. if (strcmp(fileName, ".") != 0 && strcmp(fileName, "..") != 0) {
  835. if (deletedFiles.insert(fileName).second) {
  836. std::string const fullPath =
  837. std::string(binDir).append("/").append(fileName);
  838. if (cmSystemTools::FileIsDirectory(fullPath)) {
  839. this->CleanupFiles(fullPath);
  840. cmSystemTools::RemoveADirectory(fullPath);
  841. } else {
  842. #ifdef _WIN32
  843. // Sometimes anti-virus software hangs on to new files so we
  844. // cannot delete them immediately. Try a few times.
  845. cmSystemTools::WindowsFileRetry retry =
  846. cmSystemTools::GetWindowsFileRetry();
  847. while (!cmSystemTools::RemoveFile(fullPath) && --retry.Count &&
  848. cmSystemTools::FileExists(fullPath)) {
  849. cmSystemTools::Delay(retry.Delay);
  850. }
  851. if (retry.Count == 0)
  852. #else
  853. if (!cmSystemTools::RemoveFile(fullPath))
  854. #endif
  855. {
  856. std::string m = "Remove failed on file: " + fullPath;
  857. cmSystemTools::ReportLastSystemError(m.c_str());
  858. }
  859. }
  860. }
  861. }
  862. }
  863. }
  864. void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
  865. cmStateEnums::TargetType targetType)
  866. {
  867. this->FindErrorMessage.clear();
  868. this->OutputFile.clear();
  869. std::string tmpOutputFile = "/";
  870. if (targetType == cmStateEnums::EXECUTABLE) {
  871. tmpOutputFile += targetName;
  872. tmpOutputFile +=
  873. this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  874. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  875. {
  876. tmpOutputFile +=
  877. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX");
  878. tmpOutputFile += targetName;
  879. tmpOutputFile +=
  880. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX");
  881. }
  882. // a list of directories where to search for the compilation result
  883. // at first directly in the binary dir
  884. std::vector<std::string> searchDirs;
  885. searchDirs.emplace_back();
  886. const char* config =
  887. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  888. // if a config was specified try that first
  889. if (config && config[0]) {
  890. std::string tmp = "/";
  891. tmp += config;
  892. searchDirs.push_back(std::move(tmp));
  893. }
  894. searchDirs.push_back("/Debug");
  895. #if defined(__APPLE__)
  896. std::string app = "/Debug/" + targetName + ".app";
  897. searchDirs.push_back(std::move(app));
  898. #endif
  899. searchDirs.push_back("/Development");
  900. for (std::string const& sdir : searchDirs) {
  901. std::string command = this->BinaryDirectory;
  902. command += sdir;
  903. command += tmpOutputFile;
  904. if (cmSystemTools::FileExists(command)) {
  905. this->OutputFile = cmSystemTools::CollapseFullPath(command);
  906. return;
  907. }
  908. }
  909. std::ostringstream emsg;
  910. emsg << "Unable to find the executable at any of:\n";
  911. emsg << cmWrap(" " + this->BinaryDirectory, searchDirs, tmpOutputFile, "\n")
  912. << "\n";
  913. this->FindErrorMessage = emsg.str();
  914. }