cmCoreTryCompile.cxx 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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 <array>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <set>
  8. #include <sstream>
  9. #include <utility>
  10. #include <cm/string_view>
  11. #include <cmext/string_view>
  12. #include "cmsys/Directory.hxx"
  13. #include "cmArgumentParser.h"
  14. #include "cmExportTryCompileFileGenerator.h"
  15. #include "cmGlobalGenerator.h"
  16. #include "cmMakefile.h"
  17. #include "cmMessageType.h"
  18. #include "cmOutputConverter.h"
  19. #include "cmPolicies.h"
  20. #include "cmRange.h"
  21. #include "cmState.h"
  22. #include "cmStringAlgorithms.h"
  23. #include "cmSystemTools.h"
  24. #include "cmTarget.h"
  25. #include "cmValue.h"
  26. #include "cmVersion.h"
  27. #include "cmake.h"
  28. namespace {
  29. constexpr const char* unique_binary_directory = "CMAKE_BINARY_DIR_USE_MKDTEMP";
  30. constexpr size_t lang_property_start = 0;
  31. constexpr size_t lang_property_size = 4;
  32. constexpr size_t pie_property_start = 4;
  33. constexpr size_t pie_property_size = 2;
  34. #define SETUP_LANGUAGE(name, lang) \
  35. static const std::string name[lang_property_size + pie_property_size + 1] = \
  36. { "CMAKE_" #lang "_COMPILER_EXTERNAL_TOOLCHAIN", \
  37. "CMAKE_" #lang "_COMPILER_TARGET", \
  38. "CMAKE_" #lang "_LINK_NO_PIE_SUPPORTED", \
  39. "CMAKE_" #lang "_PIE_SUPPORTED", "" }
  40. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  41. SETUP_LANGUAGE(c_properties, C);
  42. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  43. SETUP_LANGUAGE(cxx_properties, CXX);
  44. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  45. SETUP_LANGUAGE(cuda_properties, CUDA);
  46. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  47. SETUP_LANGUAGE(fortran_properties, Fortran);
  48. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  49. SETUP_LANGUAGE(hip_properties, HIP);
  50. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  51. SETUP_LANGUAGE(objc_properties, OBJC);
  52. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  53. SETUP_LANGUAGE(objcxx_properties, OBJCXX);
  54. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  55. SETUP_LANGUAGE(ispc_properties, ISPC);
  56. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  57. SETUP_LANGUAGE(swift_properties, Swift);
  58. #undef SETUP_LANGUAGE
  59. std::string const kCMAKE_CUDA_ARCHITECTURES = "CMAKE_CUDA_ARCHITECTURES";
  60. std::string const kCMAKE_CUDA_RUNTIME_LIBRARY = "CMAKE_CUDA_RUNTIME_LIBRARY";
  61. std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
  62. std::string const kCMAKE_HIP_ARCHITECTURES = "CMAKE_HIP_ARCHITECTURES";
  63. std::string const kCMAKE_HIP_RUNTIME_LIBRARY = "CMAKE_HIP_RUNTIME_LIBRARY";
  64. std::string const kCMAKE_ISPC_INSTRUCTION_SETS = "CMAKE_ISPC_INSTRUCTION_SETS";
  65. std::string const kCMAKE_ISPC_HEADER_SUFFIX = "CMAKE_ISPC_HEADER_SUFFIX";
  66. std::string const kCMAKE_LINK_SEARCH_END_STATIC =
  67. "CMAKE_LINK_SEARCH_END_STATIC";
  68. std::string const kCMAKE_LINK_SEARCH_START_STATIC =
  69. "CMAKE_LINK_SEARCH_START_STATIC";
  70. std::string const kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT =
  71. "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT";
  72. std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
  73. std::string const kCMAKE_OSX_DEPLOYMENT_TARGET = "CMAKE_OSX_DEPLOYMENT_TARGET";
  74. std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
  75. std::string const kCMAKE_APPLE_ARCH_SYSROOTS = "CMAKE_APPLE_ARCH_SYSROOTS";
  76. std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
  77. "CMAKE_POSITION_INDEPENDENT_CODE";
  78. std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
  79. std::string const kCMAKE_SYSROOT_COMPILE = "CMAKE_SYSROOT_COMPILE";
  80. std::string const kCMAKE_SYSROOT_LINK = "CMAKE_SYSROOT_LINK";
  81. std::string const kCMAKE_ARMClang_CMP0123 = "CMAKE_ARMClang_CMP0123";
  82. std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
  83. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
  84. std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
  85. "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
  86. std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
  87. std::string const kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT =
  88. "CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT";
  89. std::string const kCMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT =
  90. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT";
  91. /* GHS Multi platform variables */
  92. std::set<std::string> const ghs_platform_vars{
  93. "GHS_TARGET_PLATFORM", "GHS_PRIMARY_TARGET", "GHS_TOOLSET_ROOT",
  94. "GHS_OS_ROOT", "GHS_OS_DIR", "GHS_BSP_NAME",
  95. "GHS_OS_DIR_OPTION"
  96. };
  97. using Arguments = cmCoreTryCompile::Arguments;
  98. ArgumentParser::Continue TryCompileLangProp(Arguments& args,
  99. cm::string_view key,
  100. cm::string_view val)
  101. {
  102. args.LangProps[std::string(key)] = std::string(val);
  103. return ArgumentParser::Continue::No;
  104. }
  105. ArgumentParser::Continue TryCompileCompileDefs(Arguments& args,
  106. cm::string_view val)
  107. {
  108. cmExpandList(val, args.CompileDefs);
  109. return ArgumentParser::Continue::Yes;
  110. }
  111. #define BIND_LANG_PROPS(lang) \
  112. Bind(#lang "_STANDARD"_s, TryCompileLangProp) \
  113. .Bind(#lang "_STANDARD_REQUIRED"_s, TryCompileLangProp) \
  114. .Bind(#lang "_EXTENSIONS"_s, TryCompileLangProp)
  115. auto const TryCompileBaseArgParser =
  116. cmArgumentParser<Arguments>{}
  117. .Bind(0, &Arguments::CompileResultVariable)
  118. .Bind("SOURCES"_s, &Arguments::Sources)
  119. .Bind("CMAKE_FLAGS"_s, &Arguments::CMakeFlags)
  120. .Bind("COMPILE_DEFINITIONS"_s, TryCompileCompileDefs,
  121. ArgumentParser::ExpectAtLeast{ 0 })
  122. .Bind("LINK_LIBRARIES"_s, &Arguments::LinkLibraries)
  123. .Bind("LINK_OPTIONS"_s, &Arguments::LinkOptions)
  124. .Bind("__CMAKE_INTERNAL"_s, &Arguments::CMakeInternal)
  125. .Bind("COPY_FILE"_s, &Arguments::CopyFileTo)
  126. .Bind("COPY_FILE_ERROR"_s, &Arguments::CopyFileError)
  127. .BIND_LANG_PROPS(C)
  128. .BIND_LANG_PROPS(CUDA)
  129. .BIND_LANG_PROPS(CXX)
  130. .BIND_LANG_PROPS(HIP)
  131. .BIND_LANG_PROPS(OBJC)
  132. .BIND_LANG_PROPS(OBJCXX)
  133. /* keep semicolon on own line */;
  134. auto const TryCompileArgParser =
  135. cmArgumentParser<Arguments>{ TryCompileBaseArgParser }.Bind(
  136. "OUTPUT_VARIABLE"_s, &Arguments::OutputVariable)
  137. /* keep semicolon on own line */;
  138. auto const TryCompileOldArgParser =
  139. cmArgumentParser<Arguments>{ TryCompileArgParser }
  140. .Bind(1, &Arguments::BinaryDirectory)
  141. .Bind(2, &Arguments::SourceDirectoryOrFile)
  142. .Bind(3, &Arguments::ProjectName)
  143. .Bind(4, &Arguments::TargetName)
  144. /* keep semicolon on own line */;
  145. auto const TryRunArgParser =
  146. cmArgumentParser<Arguments>{ TryCompileBaseArgParser }
  147. .Bind("COMPILE_OUTPUT_VARIABLE"_s, &Arguments::CompileOutputVariable)
  148. .Bind("RUN_OUTPUT_VARIABLE"_s, &Arguments::RunOutputVariable)
  149. .Bind("RUN_OUTPUT_STDOUT_VARIABLE"_s, &Arguments::RunOutputStdOutVariable)
  150. .Bind("RUN_OUTPUT_STDERR_VARIABLE"_s, &Arguments::RunOutputStdErrVariable)
  151. .Bind("WORKING_DIRECTORY"_s, &Arguments::RunWorkingDirectory)
  152. .Bind("ARGS"_s, &Arguments::RunArgs)
  153. /* keep semicolon on own line */;
  154. auto const TryRunOldArgParser =
  155. cmArgumentParser<Arguments>{ TryCompileOldArgParser }
  156. .Bind("COMPILE_OUTPUT_VARIABLE"_s, &Arguments::CompileOutputVariable)
  157. .Bind("RUN_OUTPUT_VARIABLE"_s, &Arguments::RunOutputVariable)
  158. .Bind("RUN_OUTPUT_STDOUT_VARIABLE"_s, &Arguments::RunOutputStdOutVariable)
  159. .Bind("RUN_OUTPUT_STDERR_VARIABLE"_s, &Arguments::RunOutputStdErrVariable)
  160. .Bind("WORKING_DIRECTORY"_s, &Arguments::RunWorkingDirectory)
  161. .Bind("ARGS"_s, &Arguments::RunArgs)
  162. /* keep semicolon on own line */;
  163. #undef BIND_LANG_PROPS
  164. }
  165. Arguments cmCoreTryCompile::ParseArgs(
  166. const cmRange<std::vector<std::string>::const_iterator>& args,
  167. const cmArgumentParser<Arguments>& parser,
  168. std::vector<std::string>& unparsedArguments)
  169. {
  170. auto arguments = parser.Parse(args, &unparsedArguments, 0);
  171. if (!arguments.MaybeReportError(*(this->Makefile)) &&
  172. !unparsedArguments.empty()) {
  173. std::string m = "Unknown arguments:";
  174. for (const auto& i : unparsedArguments) {
  175. m = cmStrCat(m, "\n \"", i, "\"");
  176. }
  177. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, m);
  178. }
  179. return arguments;
  180. }
  181. Arguments cmCoreTryCompile::ParseArgs(
  182. cmRange<std::vector<std::string>::const_iterator> args, bool isTryRun)
  183. {
  184. std::vector<std::string> unparsedArguments;
  185. if (cmHasLiteralPrefix(*(++args.begin()), "SOURCE")) {
  186. // New signature.
  187. auto arguments =
  188. this->ParseArgs(args, isTryRun ? TryRunArgParser : TryCompileArgParser,
  189. unparsedArguments);
  190. arguments.BinaryDirectory = unique_binary_directory;
  191. return arguments;
  192. }
  193. // Old signature.
  194. auto arguments = this->ParseArgs(
  195. args, isTryRun ? TryRunOldArgParser : TryCompileOldArgParser,
  196. unparsedArguments);
  197. // For historical reasons, treat some empty-valued keyword
  198. // arguments as if they were not specified at all.
  199. if (arguments.OutputVariable && arguments.OutputVariable->empty()) {
  200. arguments.OutputVariable = cm::nullopt;
  201. }
  202. if (isTryRun) {
  203. if (arguments.CompileOutputVariable &&
  204. arguments.CompileOutputVariable->empty()) {
  205. arguments.CompileOutputVariable = cm::nullopt;
  206. }
  207. if (arguments.RunOutputVariable && arguments.RunOutputVariable->empty()) {
  208. arguments.RunOutputVariable = cm::nullopt;
  209. }
  210. if (arguments.RunOutputStdOutVariable &&
  211. arguments.RunOutputStdOutVariable->empty()) {
  212. arguments.RunOutputStdOutVariable = cm::nullopt;
  213. }
  214. if (arguments.RunOutputStdErrVariable &&
  215. arguments.RunOutputStdErrVariable->empty()) {
  216. arguments.RunOutputStdErrVariable = cm::nullopt;
  217. }
  218. if (arguments.RunWorkingDirectory &&
  219. arguments.RunWorkingDirectory->empty()) {
  220. arguments.RunWorkingDirectory = cm::nullopt;
  221. }
  222. }
  223. return arguments;
  224. }
  225. bool cmCoreTryCompile::TryCompileCode(Arguments& arguments,
  226. cmStateEnums::TargetType targetType)
  227. {
  228. this->OutputFile.clear();
  229. // which signature were we called with ?
  230. this->SrcFileSignature = true;
  231. bool useUniqueBinaryDirectory = false;
  232. std::string sourceDirectory;
  233. std::string projectName;
  234. std::string targetName;
  235. if (arguments.SourceDirectoryOrFile && arguments.ProjectName) {
  236. this->SrcFileSignature = false;
  237. sourceDirectory = *arguments.SourceDirectoryOrFile;
  238. projectName = *arguments.ProjectName;
  239. if (arguments.TargetName) {
  240. targetName = *arguments.TargetName;
  241. }
  242. } else {
  243. projectName = "CMAKE_TRY_COMPILE";
  244. /* Use a random file name to avoid rapid creation and deletion
  245. of the same executable name (some filesystems fail on that). */
  246. char targetNameBuf[64];
  247. snprintf(targetNameBuf, sizeof(targetNameBuf), "cmTC_%05x",
  248. cmSystemTools::RandomSeed() & 0xFFFFF);
  249. targetName = targetNameBuf;
  250. }
  251. if (!arguments.BinaryDirectory || arguments.BinaryDirectory->empty()) {
  252. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  253. "No <bindir> specified.");
  254. return false;
  255. }
  256. if (*arguments.BinaryDirectory == unique_binary_directory) {
  257. // leave empty until we're ready to create it, so we don't try to remove
  258. // a non-existing directory if we abort due to e.g. bad arguments
  259. this->BinaryDirectory.clear();
  260. useUniqueBinaryDirectory = true;
  261. } else {
  262. if (!cmSystemTools::FileIsFullPath(*arguments.BinaryDirectory)) {
  263. this->Makefile->IssueMessage(
  264. MessageType::FATAL_ERROR,
  265. cmStrCat("<bindir> is not an absolute path:\n '",
  266. *arguments.BinaryDirectory, "'"));
  267. return false;
  268. }
  269. this->BinaryDirectory = *arguments.BinaryDirectory;
  270. // compute the binary dir when TRY_COMPILE is called with a src file
  271. // signature
  272. if (this->SrcFileSignature) {
  273. this->BinaryDirectory += "/CMakeFiles/CMakeTmp";
  274. }
  275. }
  276. std::vector<std::string> targets;
  277. if (arguments.LinkLibraries) {
  278. for (std::string const& i : *arguments.LinkLibraries) {
  279. if (cmTarget* tgt = this->Makefile->FindTargetToUse(i)) {
  280. switch (tgt->GetType()) {
  281. case cmStateEnums::SHARED_LIBRARY:
  282. case cmStateEnums::STATIC_LIBRARY:
  283. case cmStateEnums::INTERFACE_LIBRARY:
  284. case cmStateEnums::UNKNOWN_LIBRARY:
  285. break;
  286. case cmStateEnums::EXECUTABLE:
  287. if (tgt->IsExecutableWithExports()) {
  288. break;
  289. }
  290. CM_FALLTHROUGH;
  291. default:
  292. this->Makefile->IssueMessage(
  293. MessageType::FATAL_ERROR,
  294. cmStrCat("Only libraries may be used as try_compile or try_run "
  295. "IMPORTED LINK_LIBRARIES. Got ",
  296. tgt->GetName(), " of type ",
  297. cmState::GetTargetTypeName(tgt->GetType()), "."));
  298. return false;
  299. }
  300. if (tgt->IsImported()) {
  301. targets.emplace_back(i);
  302. }
  303. }
  304. }
  305. }
  306. if (arguments.CopyFileTo && arguments.CopyFileTo->empty()) {
  307. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  308. "COPY_FILE must be followed by a file path");
  309. return false;
  310. }
  311. if (arguments.CopyFileError && arguments.CopyFileError->empty()) {
  312. this->Makefile->IssueMessage(
  313. MessageType::FATAL_ERROR,
  314. "COPY_FILE_ERROR must be followed by a variable name");
  315. return false;
  316. }
  317. if (arguments.CopyFileError && !arguments.CopyFileTo) {
  318. this->Makefile->IssueMessage(
  319. MessageType::FATAL_ERROR,
  320. "COPY_FILE_ERROR may be used only with COPY_FILE");
  321. return false;
  322. }
  323. if (arguments.Sources && arguments.Sources->empty()) {
  324. this->Makefile->IssueMessage(
  325. MessageType::FATAL_ERROR,
  326. "SOURCES must be followed by at least one source file");
  327. return false;
  328. }
  329. // only valid for srcfile signatures
  330. if (!this->SrcFileSignature) {
  331. if (!arguments.LangProps.empty()) {
  332. this->Makefile->IssueMessage(
  333. MessageType::FATAL_ERROR,
  334. cmStrCat(arguments.LangProps.begin()->first,
  335. " allowed only in source file signature."));
  336. return false;
  337. }
  338. if (!arguments.CompileDefs.empty()) {
  339. this->Makefile->IssueMessage(
  340. MessageType::FATAL_ERROR,
  341. "COMPILE_DEFINITIONS specified on a srcdir type TRY_COMPILE");
  342. return false;
  343. }
  344. if (arguments.CopyFileTo) {
  345. this->Makefile->IssueMessage(
  346. MessageType::FATAL_ERROR,
  347. "COPY_FILE specified on a srcdir type TRY_COMPILE");
  348. return false;
  349. }
  350. }
  351. // make sure the binary directory exists
  352. if (useUniqueBinaryDirectory) {
  353. this->BinaryDirectory =
  354. cmStrCat(this->Makefile->GetHomeOutputDirectory(),
  355. "/CMakeFiles/CMakeScratch/TryCompile-XXXXXX");
  356. cmSystemTools::MakeTempDirectory(this->BinaryDirectory);
  357. } else {
  358. cmSystemTools::MakeDirectory(this->BinaryDirectory);
  359. }
  360. // do not allow recursive try Compiles
  361. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
  362. std::ostringstream e;
  363. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  364. << " " << this->BinaryDirectory << "\n";
  365. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  366. return false;
  367. }
  368. std::string outFileName = this->BinaryDirectory + "/CMakeLists.txt";
  369. // which signature are we using? If we are using var srcfile bindir
  370. if (this->SrcFileSignature) {
  371. // remove any CMakeCache.txt files so we will have a clean test
  372. std::string ccFile = this->BinaryDirectory + "/CMakeCache.txt";
  373. cmSystemTools::RemoveFile(ccFile);
  374. // Choose sources.
  375. std::vector<std::string> sources;
  376. if (arguments.Sources) {
  377. sources = std::move(*arguments.Sources);
  378. } else {
  379. // TODO: ensure SourceDirectoryOrFile has a value
  380. sources.emplace_back(*arguments.SourceDirectoryOrFile);
  381. }
  382. // Detect languages to enable.
  383. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  384. std::set<std::string> testLangs;
  385. for (std::string const& si : sources) {
  386. std::string ext = cmSystemTools::GetFilenameLastExtension(si);
  387. std::string lang = gg->GetLanguageFromExtension(ext.c_str());
  388. if (!lang.empty()) {
  389. testLangs.insert(lang);
  390. } else {
  391. std::ostringstream err;
  392. err << "Unknown extension \"" << ext << "\" for file\n"
  393. << " " << si << "\n"
  394. << "try_compile() works only for enabled languages. "
  395. << "Currently these are:\n ";
  396. std::vector<std::string> langs;
  397. gg->GetEnabledLanguages(langs);
  398. err << cmJoin(langs, " ");
  399. err << "\nSee project() command to enable other languages.";
  400. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, err.str());
  401. return false;
  402. }
  403. }
  404. // when the only language is ISPC we know that the output
  405. // type must by a static library
  406. if (testLangs.size() == 1 && testLangs.count("ISPC") == 1) {
  407. targetType = cmStateEnums::STATIC_LIBRARY;
  408. }
  409. std::string const tcConfig =
  410. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  411. // we need to create a directory and CMakeLists file etc...
  412. // first create the directories
  413. sourceDirectory = this->BinaryDirectory;
  414. // now create a CMakeLists.txt file in that directory
  415. FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
  416. if (!fout) {
  417. std::ostringstream e;
  418. /* clang-format off */
  419. e << "Failed to open\n"
  420. << " " << outFileName << "\n"
  421. << cmSystemTools::GetLastSystemError();
  422. /* clang-format on */
  423. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  424. return false;
  425. }
  426. cmValue def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  427. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  428. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  429. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  430. if (def) {
  431. fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def->c_str());
  432. }
  433. /* Set MSVC runtime library policy to match our selection. */
  434. if (cmValue msvcRuntimeLibraryDefault =
  435. this->Makefile->GetDefinition(kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)) {
  436. fprintf(fout, "cmake_policy(SET CMP0091 %s)\n",
  437. !msvcRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
  438. }
  439. /* Set Watcom runtime library policy to match our selection. */
  440. if (cmValue watcomRuntimeLibraryDefault = this->Makefile->GetDefinition(
  441. kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT)) {
  442. fprintf(fout, "cmake_policy(SET CMP0136 %s)\n",
  443. !watcomRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
  444. }
  445. /* Set CUDA architectures policy to match outer project. */
  446. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0104) !=
  447. cmPolicies::NEW &&
  448. testLangs.find("CUDA") != testLangs.end() &&
  449. this->Makefile->GetSafeDefinition(kCMAKE_CUDA_ARCHITECTURES).empty()) {
  450. fprintf(fout, "cmake_policy(SET CMP0104 OLD)\n");
  451. }
  452. /* Set ARMClang cpu/arch policy to match outer project. */
  453. if (cmValue cmp0123 =
  454. this->Makefile->GetDefinition(kCMAKE_ARMClang_CMP0123)) {
  455. fprintf(fout, "cmake_policy(SET CMP0123 %s)\n",
  456. *cmp0123 == "NEW"_s ? "NEW" : "OLD");
  457. }
  458. /* Set MSVC debug information format policy to match our selection. */
  459. if (cmValue msvcDebugInformationFormatDefault =
  460. this->Makefile->GetDefinition(
  461. kCMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT)) {
  462. fprintf(fout, "cmake_policy(SET CMP0141 %s)\n",
  463. !msvcDebugInformationFormatDefault->empty() ? "NEW" : "OLD");
  464. }
  465. /* Set cache/normal variable policy to match outer project.
  466. It may affect toolchain files. */
  467. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) !=
  468. cmPolicies::NEW) {
  469. fprintf(fout, "cmake_policy(SET CMP0126 OLD)\n");
  470. }
  471. std::string projectLangs;
  472. for (std::string const& li : testLangs) {
  473. projectLangs += " " + li;
  474. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  475. std::string rulesOverrideLang = cmStrCat(rulesOverrideBase, "_", li);
  476. if (cmValue rulesOverridePath =
  477. this->Makefile->GetDefinition(rulesOverrideLang)) {
  478. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
  479. rulesOverridePath->c_str());
  480. } else if (cmValue rulesOverridePath2 =
  481. this->Makefile->GetDefinition(rulesOverrideBase)) {
  482. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
  483. rulesOverridePath2->c_str());
  484. }
  485. }
  486. fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  487. if (arguments.CMakeInternal == "ABI") {
  488. // This is the ABI detection step, also used for implicit includes.
  489. // Erase any include_directories() calls from the toolchain file so
  490. // that we do not see them as implicit. Our ABI detection source
  491. // does not include any system headers anyway.
  492. fprintf(fout,
  493. "set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES \"\")\n");
  494. // The link and compile lines for ABI detection step need to not use
  495. // response files so we can extract implicit includes given to
  496. // the underlying host compiler
  497. if (testLangs.find("CUDA") != testLangs.end()) {
  498. fprintf(fout, "set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_INCLUDES OFF)\n");
  499. fprintf(fout, "set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_LIBRARIES OFF)\n");
  500. fprintf(fout, "set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_OBJECTS OFF)\n");
  501. }
  502. }
  503. fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
  504. for (std::string const& li : testLangs) {
  505. std::string langFlags = "CMAKE_" + li + "_FLAGS";
  506. cmValue flags = this->Makefile->GetDefinition(langFlags);
  507. fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
  508. cmOutputConverter::EscapeForCMake(*flags).c_str());
  509. fprintf(fout,
  510. "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
  511. " ${COMPILE_DEFINITIONS}\")\n",
  512. li.c_str(), li.c_str());
  513. }
  514. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
  515. case cmPolicies::WARN:
  516. if (this->Makefile->PolicyOptionalWarningEnabled(
  517. "CMAKE_POLICY_WARNING_CMP0066")) {
  518. std::ostringstream w;
  519. /* clang-format off */
  520. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
  521. "For compatibility with older versions of CMake, try_compile "
  522. "is not honoring caller config-specific compiler flags "
  523. "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
  524. ;
  525. /* clang-format on */
  526. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  527. }
  528. CM_FALLTHROUGH;
  529. case cmPolicies::OLD:
  530. // OLD behavior is to do nothing.
  531. break;
  532. case cmPolicies::REQUIRED_IF_USED:
  533. case cmPolicies::REQUIRED_ALWAYS:
  534. this->Makefile->IssueMessage(
  535. MessageType::FATAL_ERROR,
  536. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0066));
  537. CM_FALLTHROUGH;
  538. case cmPolicies::NEW: {
  539. // NEW behavior is to pass config-specific compiler flags.
  540. static std::string const cfgDefault = "DEBUG";
  541. std::string const cfg =
  542. !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
  543. for (std::string const& li : testLangs) {
  544. std::string const langFlagsCfg =
  545. cmStrCat("CMAKE_", li, "_FLAGS_", cfg);
  546. cmValue flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
  547. fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
  548. cmOutputConverter::EscapeForCMake(*flagsCfg).c_str());
  549. }
  550. } break;
  551. }
  552. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
  553. case cmPolicies::WARN:
  554. if (this->Makefile->PolicyOptionalWarningEnabled(
  555. "CMAKE_POLICY_WARNING_CMP0056")) {
  556. std::ostringstream w;
  557. /* clang-format off */
  558. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0056) << "\n"
  559. "For compatibility with older versions of CMake, try_compile "
  560. "is not honoring caller link flags (e.g. CMAKE_EXE_LINKER_FLAGS) "
  561. "in the test project."
  562. ;
  563. /* clang-format on */
  564. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  565. }
  566. CM_FALLTHROUGH;
  567. case cmPolicies::OLD:
  568. // OLD behavior is to do nothing.
  569. break;
  570. case cmPolicies::REQUIRED_IF_USED:
  571. case cmPolicies::REQUIRED_ALWAYS:
  572. this->Makefile->IssueMessage(
  573. MessageType::FATAL_ERROR,
  574. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0056));
  575. CM_FALLTHROUGH;
  576. case cmPolicies::NEW:
  577. // NEW behavior is to pass linker flags.
  578. {
  579. cmValue exeLinkFlags =
  580. this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
  581. fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
  582. cmOutputConverter::EscapeForCMake(*exeLinkFlags).c_str());
  583. }
  584. break;
  585. }
  586. fprintf(fout,
  587. "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
  588. " ${EXE_LINKER_FLAGS}\")\n");
  589. fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
  590. fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
  591. fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
  592. // handle any compile flags we need to pass on
  593. if (!arguments.CompileDefs.empty()) {
  594. // Pass using bracket arguments to preserve content.
  595. fprintf(fout, "add_definitions([==[%s]==])\n",
  596. cmJoin(arguments.CompileDefs, "]==] [==[").c_str());
  597. }
  598. if (!targets.empty()) {
  599. std::string fname = "/" + std::string(targetName) + "Targets.cmake";
  600. cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile,
  601. testLangs);
  602. tcfg.SetExportFile((this->BinaryDirectory + fname).c_str());
  603. tcfg.SetConfig(tcConfig);
  604. if (!tcfg.GenerateImportFile()) {
  605. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  606. "could not write export file.");
  607. fclose(fout);
  608. return false;
  609. }
  610. fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  611. fname.c_str());
  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. /* Set the appropriate policy information for PIE link flags */
  620. fprintf(fout, "cmake_policy(SET CMP0083 %s)\n",
  621. this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
  622. cmPolicies::NEW
  623. ? "NEW"
  624. : "OLD");
  625. // Workaround for -Wl,-headerpad_max_install_names issue until we can avoid
  626. // adding that flag in the platform and compiler language files
  627. fprintf(fout,
  628. "include(\"${CMAKE_ROOT}/Modules/Internal/"
  629. "HeaderpadWorkaround.cmake\")\n");
  630. if (targetType == cmStateEnums::EXECUTABLE) {
  631. /* Put the executable at a known location (for COPY_FILE). */
  632. fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  633. this->BinaryDirectory.c_str());
  634. /* Create the actual executable. */
  635. fprintf(fout, "add_executable(%s", targetName.c_str());
  636. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  637. {
  638. /* Put the static library at a known location (for COPY_FILE). */
  639. fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
  640. this->BinaryDirectory.c_str());
  641. /* Create the actual static library. */
  642. fprintf(fout, "add_library(%s STATIC", targetName.c_str());
  643. }
  644. for (std::string const& si : sources) {
  645. fprintf(fout, " \"%s\"", si.c_str());
  646. // Add dependencies on any non-temporary sources.
  647. if (!IsTemporary(si)) {
  648. this->Makefile->AddCMakeDependFile(si);
  649. }
  650. }
  651. fprintf(fout, ")\n");
  652. bool warnCMP0067 = false;
  653. bool honorStandard = true;
  654. if (arguments.LangProps.empty()) {
  655. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0067)) {
  656. case cmPolicies::WARN:
  657. warnCMP0067 = this->Makefile->PolicyOptionalWarningEnabled(
  658. "CMAKE_POLICY_WARNING_CMP0067");
  659. CM_FALLTHROUGH;
  660. case cmPolicies::OLD:
  661. // OLD behavior is to not honor the language standard variables.
  662. honorStandard = false;
  663. break;
  664. case cmPolicies::REQUIRED_IF_USED:
  665. case cmPolicies::REQUIRED_ALWAYS:
  666. this->Makefile->IssueMessage(
  667. MessageType::FATAL_ERROR,
  668. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0067));
  669. break;
  670. case cmPolicies::NEW:
  671. // NEW behavior is to honor the language standard variables.
  672. // We already initialized honorStandard to true.
  673. break;
  674. }
  675. }
  676. std::vector<std::string> warnCMP0067Variables;
  677. if (honorStandard || warnCMP0067) {
  678. static std::array<std::string, 6> const possibleLangs{
  679. { "C", "CXX", "CUDA", "HIP", "OBJC", "OBJCXX" }
  680. };
  681. static std::array<cm::string_view, 3> const langPropSuffixes{
  682. { "_STANDARD"_s, "_STANDARD_REQUIRED"_s, "_EXTENSIONS"_s }
  683. };
  684. for (std::string const& lang : possibleLangs) {
  685. if (testLangs.find(lang) == testLangs.end()) {
  686. continue;
  687. }
  688. for (cm::string_view propSuffix : langPropSuffixes) {
  689. std::string langProp = cmStrCat(lang, propSuffix);
  690. if (!arguments.LangProps.count(langProp)) {
  691. std::string langPropVar = cmStrCat("CMAKE_"_s, langProp);
  692. std::string value = this->Makefile->GetSafeDefinition(langPropVar);
  693. if (warnCMP0067 && !value.empty()) {
  694. value.clear();
  695. warnCMP0067Variables.emplace_back(langPropVar);
  696. }
  697. if (!value.empty()) {
  698. arguments.LangProps[langProp] = value;
  699. }
  700. }
  701. }
  702. }
  703. }
  704. if (!warnCMP0067Variables.empty()) {
  705. std::ostringstream w;
  706. /* clang-format off */
  707. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0067) << "\n"
  708. "For compatibility with older versions of CMake, try_compile "
  709. "is not honoring language standard variables in the test project:\n"
  710. ;
  711. /* clang-format on */
  712. for (std::string const& vi : warnCMP0067Variables) {
  713. w << " " << vi << "\n";
  714. }
  715. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  716. }
  717. for (auto const& p : arguments.LangProps) {
  718. if (p.second.empty()) {
  719. continue;
  720. }
  721. fprintf(fout, "set_property(TARGET %s PROPERTY %s %s)\n",
  722. targetName.c_str(),
  723. cmOutputConverter::EscapeForCMake(p.first).c_str(),
  724. cmOutputConverter::EscapeForCMake(p.second).c_str());
  725. }
  726. if (!arguments.LinkOptions.empty()) {
  727. std::vector<std::string> options;
  728. options.reserve(arguments.LinkOptions.size());
  729. for (const auto& option : arguments.LinkOptions) {
  730. options.emplace_back(cmOutputConverter::EscapeForCMake(option));
  731. }
  732. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  733. fprintf(fout,
  734. "set_property(TARGET %s PROPERTY STATIC_LIBRARY_OPTIONS %s)\n",
  735. targetName.c_str(), cmJoin(options, " ").c_str());
  736. } else {
  737. fprintf(fout, "target_link_options(%s PRIVATE %s)\n",
  738. targetName.c_str(), cmJoin(options, " ").c_str());
  739. }
  740. }
  741. if (arguments.LinkLibraries) {
  742. std::string libsToLink = " ";
  743. for (std::string const& i : *arguments.LinkLibraries) {
  744. libsToLink += "\"" + cmTrimWhitespace(i) + "\" ";
  745. }
  746. fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
  747. libsToLink.c_str());
  748. } else {
  749. fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
  750. targetName.c_str());
  751. }
  752. fclose(fout);
  753. }
  754. // Forward a set of variables to the inner project cache.
  755. if ((this->SrcFileSignature ||
  756. this->Makefile->GetPolicyStatus(cmPolicies::CMP0137) ==
  757. cmPolicies::NEW) &&
  758. !this->Makefile->IsOn("CMAKE_TRY_COMPILE_NO_PLATFORM_VARIABLES")) {
  759. std::set<std::string> vars;
  760. vars.insert(&c_properties[lang_property_start],
  761. &c_properties[lang_property_start + lang_property_size]);
  762. vars.insert(&cxx_properties[lang_property_start],
  763. &cxx_properties[lang_property_start + lang_property_size]);
  764. vars.insert(&cuda_properties[lang_property_start],
  765. &cuda_properties[lang_property_start + lang_property_size]);
  766. vars.insert(&fortran_properties[lang_property_start],
  767. &fortran_properties[lang_property_start + lang_property_size]);
  768. vars.insert(&hip_properties[lang_property_start],
  769. &hip_properties[lang_property_start + lang_property_size]);
  770. vars.insert(&objc_properties[lang_property_start],
  771. &objc_properties[lang_property_start + lang_property_size]);
  772. vars.insert(&objcxx_properties[lang_property_start],
  773. &objcxx_properties[lang_property_start + lang_property_size]);
  774. vars.insert(&ispc_properties[lang_property_start],
  775. &ispc_properties[lang_property_start + lang_property_size]);
  776. vars.insert(&swift_properties[lang_property_start],
  777. &swift_properties[lang_property_start + lang_property_size]);
  778. vars.insert(kCMAKE_CUDA_ARCHITECTURES);
  779. vars.insert(kCMAKE_CUDA_RUNTIME_LIBRARY);
  780. vars.insert(kCMAKE_ENABLE_EXPORTS);
  781. vars.insert(kCMAKE_HIP_ARCHITECTURES);
  782. vars.insert(kCMAKE_HIP_RUNTIME_LIBRARY);
  783. vars.insert(kCMAKE_ISPC_INSTRUCTION_SETS);
  784. vars.insert(kCMAKE_ISPC_HEADER_SUFFIX);
  785. vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
  786. vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
  787. vars.insert(kCMAKE_OSX_ARCHITECTURES);
  788. vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
  789. vars.insert(kCMAKE_OSX_SYSROOT);
  790. vars.insert(kCMAKE_APPLE_ARCH_SYSROOTS);
  791. vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
  792. vars.insert(kCMAKE_SYSROOT);
  793. vars.insert(kCMAKE_SYSROOT_COMPILE);
  794. vars.insert(kCMAKE_SYSROOT_LINK);
  795. vars.insert(kCMAKE_WARN_DEPRECATED);
  796. vars.emplace("CMAKE_MSVC_RUNTIME_LIBRARY"_s);
  797. vars.emplace("CMAKE_WATCOM_RUNTIME_LIBRARY"_s);
  798. vars.emplace("CMAKE_MSVC_DEBUG_INFORMATION_FORMAT"_s);
  799. if (cmValue varListStr = this->Makefile->GetDefinition(
  800. kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
  801. std::vector<std::string> varList = cmExpandedList(*varListStr);
  802. vars.insert(varList.begin(), varList.end());
  803. }
  804. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
  805. cmPolicies::NEW) {
  806. // To ensure full support of PIE, propagate cache variables
  807. // driving the link options
  808. vars.insert(&c_properties[pie_property_start],
  809. &c_properties[pie_property_start + pie_property_size]);
  810. vars.insert(&cxx_properties[pie_property_start],
  811. &cxx_properties[pie_property_start + pie_property_size]);
  812. vars.insert(&cuda_properties[pie_property_start],
  813. &cuda_properties[pie_property_start + pie_property_size]);
  814. vars.insert(&fortran_properties[pie_property_start],
  815. &fortran_properties[pie_property_start + pie_property_size]);
  816. vars.insert(&hip_properties[pie_property_start],
  817. &hip_properties[pie_property_start + pie_property_size]);
  818. vars.insert(&objc_properties[pie_property_start],
  819. &objc_properties[pie_property_start + pie_property_size]);
  820. vars.insert(&objcxx_properties[pie_property_start],
  821. &objcxx_properties[pie_property_start + pie_property_size]);
  822. vars.insert(&ispc_properties[pie_property_start],
  823. &ispc_properties[pie_property_start + pie_property_size]);
  824. vars.insert(&swift_properties[pie_property_start],
  825. &swift_properties[pie_property_start + pie_property_size]);
  826. }
  827. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  828. So the user can set CMAKE_OSX_ARCHITECTURES to i386;ppc and then set
  829. CMAKE_TRY_COMPILE_OSX_ARCHITECTURES first to i386 and then to ppc to
  830. have the tests run for each specific architecture. Since
  831. cmLocalGenerator doesn't allow building for "the other"
  832. architecture only via CMAKE_OSX_ARCHITECTURES.
  833. */
  834. if (cmValue tcArchs = this->Makefile->GetDefinition(
  835. kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES)) {
  836. vars.erase(kCMAKE_OSX_ARCHITECTURES);
  837. std::string flag = "-DCMAKE_OSX_ARCHITECTURES=" + *tcArchs;
  838. arguments.CMakeFlags.emplace_back(std::move(flag));
  839. }
  840. for (std::string const& var : vars) {
  841. if (cmValue val = this->Makefile->GetDefinition(var)) {
  842. std::string flag = "-D" + var + "=" + *val;
  843. arguments.CMakeFlags.emplace_back(std::move(flag));
  844. }
  845. }
  846. }
  847. if (this->Makefile->GetState()->UseGhsMultiIDE()) {
  848. // Forward the GHS variables to the inner project cache.
  849. for (std::string const& var : ghs_platform_vars) {
  850. if (cmValue val = this->Makefile->GetDefinition(var)) {
  851. std::string flag = "-D" + var + "=" + "'" + *val + "'";
  852. arguments.CMakeFlags.emplace_back(std::move(flag));
  853. }
  854. }
  855. }
  856. bool erroroc = cmSystemTools::GetErrorOccurredFlag();
  857. cmSystemTools::ResetErrorOccurredFlag();
  858. std::string output;
  859. // actually do the try compile now that everything is setup
  860. int res = this->Makefile->TryCompile(
  861. sourceDirectory, this->BinaryDirectory, projectName, targetName,
  862. this->SrcFileSignature, cmake::NO_BUILD_PARALLEL_LEVEL,
  863. &arguments.CMakeFlags, output);
  864. if (erroroc) {
  865. cmSystemTools::SetErrorOccurred();
  866. }
  867. // set the result var to the return value to indicate success or failure
  868. this->Makefile->AddCacheDefinition(
  869. *arguments.CompileResultVariable, (res == 0 ? "TRUE" : "FALSE"),
  870. "Result of TRY_COMPILE", cmStateEnums::INTERNAL);
  871. if (arguments.OutputVariable) {
  872. this->Makefile->AddDefinition(*arguments.OutputVariable, output);
  873. }
  874. if (this->SrcFileSignature) {
  875. std::string copyFileErrorMessage;
  876. this->FindOutputFile(targetName, targetType);
  877. if ((res == 0) && arguments.CopyFileTo) {
  878. std::string const& copyFile = *arguments.CopyFileTo;
  879. if (this->OutputFile.empty() ||
  880. !cmSystemTools::CopyFileAlways(this->OutputFile, copyFile)) {
  881. std::ostringstream emsg;
  882. /* clang-format off */
  883. emsg << "Cannot copy output executable\n"
  884. << " '" << this->OutputFile << "'\n"
  885. << "to destination specified by COPY_FILE:\n"
  886. << " '" << copyFile << "'\n";
  887. /* clang-format on */
  888. if (!this->FindErrorMessage.empty()) {
  889. emsg << this->FindErrorMessage;
  890. }
  891. if (!arguments.CopyFileError) {
  892. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, emsg.str());
  893. return false;
  894. }
  895. copyFileErrorMessage = emsg.str();
  896. }
  897. }
  898. if (arguments.CopyFileError) {
  899. std::string const& copyFileError = *arguments.CopyFileError;
  900. this->Makefile->AddDefinition(copyFileError, copyFileErrorMessage);
  901. }
  902. }
  903. return res == 0;
  904. }
  905. bool cmCoreTryCompile::IsTemporary(std::string const& path)
  906. {
  907. return ((path.find("CMakeTmp") != std::string::npos) ||
  908. (path.find("CMakeScratch") != std::string::npos));
  909. }
  910. void cmCoreTryCompile::CleanupFiles(std::string const& binDir)
  911. {
  912. if (binDir.empty()) {
  913. return;
  914. }
  915. if (!IsTemporary(binDir)) {
  916. cmSystemTools::Error(
  917. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  918. "CMakeTmp or CMakeScratch: \"" +
  919. binDir + "\"");
  920. return;
  921. }
  922. cmsys::Directory dir;
  923. dir.Load(binDir);
  924. std::set<std::string> deletedFiles;
  925. for (unsigned long i = 0; i < dir.GetNumberOfFiles(); ++i) {
  926. const char* fileName = dir.GetFile(i);
  927. if (strcmp(fileName, ".") != 0 && strcmp(fileName, "..") != 0 &&
  928. // Do not delete NFS temporary files.
  929. !cmHasPrefix(fileName, ".nfs")) {
  930. if (deletedFiles.insert(fileName).second) {
  931. std::string const fullPath =
  932. std::string(binDir).append("/").append(fileName);
  933. if (cmSystemTools::FileIsSymlink(fullPath)) {
  934. cmSystemTools::RemoveFile(fullPath);
  935. } else if (cmSystemTools::FileIsDirectory(fullPath)) {
  936. this->CleanupFiles(fullPath);
  937. cmSystemTools::RemoveADirectory(fullPath);
  938. } else {
  939. #ifdef _WIN32
  940. // Sometimes anti-virus software hangs on to new files so we
  941. // cannot delete them immediately. Try a few times.
  942. cmSystemTools::WindowsFileRetry retry =
  943. cmSystemTools::GetWindowsFileRetry();
  944. cmsys::Status status;
  945. while (!((status = cmSystemTools::RemoveFile(fullPath))) &&
  946. --retry.Count && cmSystemTools::FileExists(fullPath)) {
  947. cmSystemTools::Delay(retry.Delay);
  948. }
  949. if (retry.Count == 0)
  950. #else
  951. cmsys::Status status = cmSystemTools::RemoveFile(fullPath);
  952. if (!status)
  953. #endif
  954. {
  955. this->Makefile->IssueMessage(
  956. MessageType::FATAL_ERROR,
  957. cmStrCat("The file:\n ", fullPath,
  958. "\ncould not be removed:\n ", status.GetString()));
  959. }
  960. }
  961. }
  962. }
  963. }
  964. if (binDir.find("CMakeScratch") != std::string::npos) {
  965. cmSystemTools::RemoveADirectory(binDir);
  966. }
  967. }
  968. void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
  969. cmStateEnums::TargetType targetType)
  970. {
  971. this->FindErrorMessage.clear();
  972. this->OutputFile.clear();
  973. std::string tmpOutputFile = "/";
  974. if (targetType == cmStateEnums::EXECUTABLE) {
  975. tmpOutputFile += targetName;
  976. tmpOutputFile +=
  977. this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
  978. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  979. {
  980. tmpOutputFile +=
  981. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX");
  982. tmpOutputFile += targetName;
  983. tmpOutputFile +=
  984. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX");
  985. }
  986. // a list of directories where to search for the compilation result
  987. // at first directly in the binary dir
  988. std::vector<std::string> searchDirs;
  989. searchDirs.emplace_back();
  990. cmValue config =
  991. this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  992. // if a config was specified try that first
  993. if (cmNonempty(config)) {
  994. std::string tmp = cmStrCat('/', *config);
  995. searchDirs.emplace_back(std::move(tmp));
  996. }
  997. searchDirs.emplace_back("/Debug");
  998. // handle app-bundles (for targeting apple-platforms)
  999. std::string app = "/" + targetName + ".app";
  1000. if (cmNonempty(config)) {
  1001. std::string tmp = cmStrCat('/', *config, app);
  1002. searchDirs.emplace_back(std::move(tmp));
  1003. }
  1004. std::string tmp = "/Debug" + app;
  1005. searchDirs.emplace_back(std::move(tmp));
  1006. searchDirs.emplace_back(std::move(app));
  1007. searchDirs.emplace_back("/Development");
  1008. for (std::string const& sdir : searchDirs) {
  1009. std::string command = cmStrCat(this->BinaryDirectory, sdir, tmpOutputFile);
  1010. if (cmSystemTools::FileExists(command)) {
  1011. this->OutputFile = cmSystemTools::CollapseFullPath(command);
  1012. return;
  1013. }
  1014. }
  1015. std::ostringstream emsg;
  1016. emsg << "Unable to find the executable at any of:\n";
  1017. emsg << cmWrap(" " + this->BinaryDirectory, searchDirs, tmpOutputFile, "\n")
  1018. << "\n";
  1019. this->FindErrorMessage = emsg.str();
  1020. }