cmake.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifndef cmake_h
  4. #define cmake_h
  5. #include "cmConfigure.h" // IWYU pragma: keep
  6. #include <map>
  7. #include <set>
  8. #include <string>
  9. #include <vector>
  10. #include "cmInstalledFile.h"
  11. #include "cmListFileCache.h"
  12. #include "cmStateSnapshot.h"
  13. #include "cmStateTypes.h"
  14. #if defined(CMAKE_BUILD_WITH_CMAKE)
  15. #include "cm_jsoncpp_value.h"
  16. #endif
  17. class cmExternalMakefileProjectGeneratorFactory;
  18. class cmFileTimeComparison;
  19. class cmGlobalGenerator;
  20. class cmGlobalGeneratorFactory;
  21. class cmMakefile;
  22. class cmMessenger;
  23. class cmState;
  24. class cmVariableWatch;
  25. struct cmDocumentationEntry;
  26. /** \brief Represents a cmake invocation.
  27. *
  28. * This class represents a cmake invocation. It is the top level class when
  29. * running cmake. Most cmake based GUIs should primarily create an instance
  30. * of this class and communicate with it.
  31. *
  32. * The basic process for a GUI is as follows:
  33. *
  34. * -# Create a cmake instance
  35. * -# Set the Home directories, generator, and cmake command. this
  36. * can be done using the Set methods or by using SetArgs and passing in
  37. * command line arguments.
  38. * -# Load the cache by calling LoadCache (duh)
  39. * -# if you are using command line arguments with -D or -C flags then
  40. * call SetCacheArgs (or if for some other reason you want to modify the
  41. * cache), do it now.
  42. * -# Finally call Configure
  43. * -# Let the user change values and go back to step 5
  44. * -# call Generate
  45. * If your GUI allows the user to change the home directories then
  46. * you must at a minimum redo steps 2 through 7.
  47. */
  48. class cmake
  49. {
  50. CM_DISABLE_COPY(cmake)
  51. public:
  52. enum Role
  53. {
  54. RoleInternal, // no commands
  55. RoleScript, // script commands
  56. RoleProject // all commands
  57. };
  58. enum MessageType
  59. {
  60. AUTHOR_WARNING,
  61. AUTHOR_ERROR,
  62. FATAL_ERROR,
  63. INTERNAL_ERROR,
  64. MESSAGE,
  65. WARNING,
  66. LOG,
  67. DEPRECATION_ERROR,
  68. DEPRECATION_WARNING
  69. };
  70. enum DiagLevel
  71. {
  72. DIAG_IGNORE,
  73. DIAG_WARN,
  74. DIAG_ERROR
  75. };
  76. /** \brief Describes the working modes of cmake */
  77. enum WorkingMode
  78. {
  79. NORMAL_MODE, ///< Cmake runs to create project files
  80. /** \brief Script mode (started by using -P).
  81. *
  82. * In script mode there is no generator and no cache. Also,
  83. * languages are not enabled, so add_executable and things do
  84. * nothing.
  85. */
  86. SCRIPT_MODE,
  87. /** \brief A pkg-config like mode
  88. *
  89. * In this mode cmake just searches for a package and prints the results to
  90. * stdout. This is similar to SCRIPT_MODE, but commands like add_library()
  91. * work too, since they may be used e.g. in exported target files. Started
  92. * via --find-package.
  93. */
  94. FIND_PACKAGE_MODE
  95. };
  96. struct GeneratorInfo
  97. {
  98. std::string name;
  99. std::string baseName;
  100. std::string extraName;
  101. bool supportsToolset;
  102. bool supportsPlatform;
  103. bool isAlias;
  104. };
  105. typedef std::map<std::string, cmInstalledFile> InstalledFilesMap;
  106. /// Default constructor
  107. cmake(Role role);
  108. /// Destructor
  109. ~cmake();
  110. #if defined(CMAKE_BUILD_WITH_CMAKE)
  111. Json::Value ReportCapabilitiesJson(bool haveServerMode) const;
  112. #endif
  113. std::string ReportCapabilities(bool haveServerMode) const;
  114. static const char* GetCMakeFilesDirectory() { return "/CMakeFiles"; }
  115. static const char* GetCMakeFilesDirectoryPostSlash()
  116. {
  117. return "CMakeFiles/";
  118. }
  119. //@{
  120. /**
  121. * Set/Get the home directory (or output directory) in the project. The
  122. * home directory is the top directory of the project. It is the
  123. * path-to-source cmake was run with.
  124. */
  125. void SetHomeDirectory(const std::string& dir);
  126. const char* GetHomeDirectory() const;
  127. void SetHomeOutputDirectory(const std::string& dir);
  128. const char* GetHomeOutputDirectory() const;
  129. //@}
  130. /**
  131. * Handle a command line invocation of cmake.
  132. */
  133. int Run(const std::vector<std::string>& args)
  134. {
  135. return this->Run(args, false);
  136. }
  137. int Run(const std::vector<std::string>& args, bool noconfigure);
  138. /**
  139. * Run the global generator Generate step.
  140. */
  141. int Generate();
  142. /**
  143. * Configure the cmMakefiles. This routine will create a GlobalGenerator if
  144. * one has not already been set. It will then Call Configure on the
  145. * GlobalGenerator. This in turn will read in an process all the CMakeList
  146. * files for the tree. It will not produce any actual Makefiles, or
  147. * workspaces. Generate does that. */
  148. int Configure();
  149. int ActualConfigure();
  150. ///! Break up a line like VAR:type="value" into var, type and value
  151. static bool ParseCacheEntry(const std::string& entry, std::string& var,
  152. std::string& value,
  153. cmStateEnums::CacheEntryType& type);
  154. int LoadCache();
  155. bool LoadCache(const std::string& path);
  156. bool LoadCache(const std::string& path, bool internal,
  157. std::set<std::string>& excludes,
  158. std::set<std::string>& includes);
  159. bool SaveCache(const std::string& path);
  160. bool DeleteCache(const std::string& path);
  161. void PreLoadCMakeFiles();
  162. ///! Create a GlobalGenerator
  163. cmGlobalGenerator* CreateGlobalGenerator(const std::string& name);
  164. ///! Return the global generator assigned to this instance of cmake
  165. cmGlobalGenerator* GetGlobalGenerator() { return this->GlobalGenerator; }
  166. ///! Return the global generator assigned to this instance of cmake, const
  167. const cmGlobalGenerator* GetGlobalGenerator() const
  168. {
  169. return this->GlobalGenerator;
  170. }
  171. ///! Return the full path to where the CMakeCache.txt file should be.
  172. static std::string FindCacheFile(const std::string& binaryDir);
  173. ///! Return the global generator assigned to this instance of cmake
  174. void SetGlobalGenerator(cmGlobalGenerator*);
  175. ///! Get the names of the current registered generators
  176. void GetRegisteredGenerators(std::vector<GeneratorInfo>& generators) const;
  177. ///! Set the name of the selected generator-specific instance.
  178. void SetGeneratorInstance(std::string const& instance)
  179. {
  180. this->GeneratorInstance = instance;
  181. }
  182. ///! Set the name of the selected generator-specific platform.
  183. void SetGeneratorPlatform(std::string const& ts)
  184. {
  185. this->GeneratorPlatform = ts;
  186. }
  187. ///! Set the name of the selected generator-specific toolset.
  188. void SetGeneratorToolset(std::string const& ts)
  189. {
  190. this->GeneratorToolset = ts;
  191. }
  192. const std::vector<std::string>& GetSourceExtensions() const
  193. {
  194. return this->SourceFileExtensions;
  195. }
  196. const std::vector<std::string>& GetHeaderExtensions() const
  197. {
  198. return this->HeaderFileExtensions;
  199. }
  200. /**
  201. * Given a variable name, return its value (as a string).
  202. */
  203. const char* GetCacheDefinition(const std::string&) const;
  204. ///! Add an entry into the cache
  205. void AddCacheEntry(const std::string& key, const char* value,
  206. const char* helpString, int type);
  207. /**
  208. * Get the system information and write it to the file specified
  209. */
  210. int GetSystemInformation(std::vector<std::string>&);
  211. ///! Parse command line arguments
  212. void SetArgs(const std::vector<std::string>&,
  213. bool directoriesSetBefore = false);
  214. ///! Is this cmake running as a result of a TRY_COMPILE command
  215. bool GetIsInTryCompile() const;
  216. void SetIsInTryCompile(bool b);
  217. ///! Parse command line arguments that might set cache values
  218. bool SetCacheArgs(const std::vector<std::string>&);
  219. typedef void (*ProgressCallbackType)(const char* msg, float progress, void*);
  220. /**
  221. * Set the function used by GUIs to receive progress updates
  222. * Function gets passed: message as a const char*, a progress
  223. * amount ranging from 0 to 1.0 and client data. The progress
  224. * number provided may be negative in cases where a message is
  225. * to be displayed without any progress percentage.
  226. */
  227. void SetProgressCallback(ProgressCallbackType f, void* clientData = nullptr);
  228. ///! this is called by generators to update the progress
  229. void UpdateProgress(const char* msg, float prog);
  230. ///! Get the variable watch object
  231. cmVariableWatch* GetVariableWatch() { return this->VariableWatch; }
  232. void GetGeneratorDocumentation(std::vector<cmDocumentationEntry>&);
  233. ///! Set/Get a property of this target file
  234. void SetProperty(const std::string& prop, const char* value);
  235. void AppendProperty(const std::string& prop, const char* value,
  236. bool asString = false);
  237. const char* GetProperty(const std::string& prop);
  238. bool GetPropertyAsBool(const std::string& prop);
  239. ///! Get or create an cmInstalledFile instance and return a pointer to it
  240. cmInstalledFile* GetOrCreateInstalledFile(cmMakefile* mf,
  241. const std::string& name);
  242. cmInstalledFile const* GetInstalledFile(const std::string& name) const;
  243. InstalledFilesMap const& GetInstalledFiles() const
  244. {
  245. return this->InstalledFiles;
  246. }
  247. ///! Do all the checks before running configure
  248. int DoPreConfigureChecks();
  249. void SetWorkingMode(WorkingMode mode) { this->CurrentWorkingMode = mode; }
  250. WorkingMode GetWorkingMode() { return this->CurrentWorkingMode; }
  251. ///! Debug the try compile stuff by not deleting the files
  252. bool GetDebugTryCompile() { return this->DebugTryCompile; }
  253. void DebugTryCompileOn() { this->DebugTryCompile = true; }
  254. /**
  255. * Generate CMAKE_ROOT and CMAKE_COMMAND cache entries
  256. */
  257. int AddCMakePaths();
  258. /**
  259. * Get the file comparison class
  260. */
  261. cmFileTimeComparison* GetFileComparison() { return this->FileComparison; }
  262. // Do we want debug output during the cmake run.
  263. bool GetDebugOutput() { return this->DebugOutput; }
  264. void SetDebugOutputOn(bool b) { this->DebugOutput = b; }
  265. // Do we want trace output during the cmake run.
  266. bool GetTrace() { return this->Trace; }
  267. void SetTrace(bool b) { this->Trace = b; }
  268. bool GetTraceExpand() { return this->TraceExpand; }
  269. void SetTraceExpand(bool b) { this->TraceExpand = b; }
  270. void AddTraceSource(std::string const& file)
  271. {
  272. this->TraceOnlyThisSources.push_back(file);
  273. }
  274. std::vector<std::string> const& GetTraceSources() const
  275. {
  276. return this->TraceOnlyThisSources;
  277. }
  278. bool GetWarnUninitialized() { return this->WarnUninitialized; }
  279. void SetWarnUninitialized(bool b) { this->WarnUninitialized = b; }
  280. bool GetWarnUnused() { return this->WarnUnused; }
  281. void SetWarnUnused(bool b) { this->WarnUnused = b; }
  282. bool GetWarnUnusedCli() { return this->WarnUnusedCli; }
  283. void SetWarnUnusedCli(bool b) { this->WarnUnusedCli = b; }
  284. bool GetCheckSystemVars() { return this->CheckSystemVars; }
  285. void SetCheckSystemVars(bool b) { this->CheckSystemVars = b; }
  286. void MarkCliAsUsed(const std::string& variable);
  287. /** Get the list of configurations (in upper case) considered to be
  288. debugging configurations.*/
  289. std::vector<std::string> GetDebugConfigs();
  290. void SetCMakeEditCommand(std::string const& s)
  291. {
  292. this->CMakeEditCommand = s;
  293. }
  294. std::string const& GetCMakeEditCommand() const
  295. {
  296. return this->CMakeEditCommand;
  297. }
  298. cmMessenger* GetMessenger() const;
  299. /*
  300. * Get the state of the suppression of developer (author) warnings.
  301. * Returns false, by default, if developer warnings should be shown, true
  302. * otherwise.
  303. */
  304. bool GetSuppressDevWarnings() const;
  305. /*
  306. * Set the state of the suppression of developer (author) warnings.
  307. */
  308. void SetSuppressDevWarnings(bool v);
  309. /*
  310. * Get the state of the suppression of deprecated warnings.
  311. * Returns false, by default, if deprecated warnings should be shown, true
  312. * otherwise.
  313. */
  314. bool GetSuppressDeprecatedWarnings() const;
  315. /*
  316. * Set the state of the suppression of deprecated warnings.
  317. */
  318. void SetSuppressDeprecatedWarnings(bool v);
  319. /*
  320. * Get the state of treating developer (author) warnings as errors.
  321. * Returns false, by default, if warnings should not be treated as errors,
  322. * true otherwise.
  323. */
  324. bool GetDevWarningsAsErrors() const;
  325. /**
  326. * Set the state of treating developer (author) warnings as errors.
  327. */
  328. void SetDevWarningsAsErrors(bool v);
  329. /*
  330. * Get the state of treating deprecated warnings as errors.
  331. * Returns false, by default, if warnings should not be treated as errors,
  332. * true otherwise.
  333. */
  334. bool GetDeprecatedWarningsAsErrors() const;
  335. /**
  336. * Set the state of treating developer (author) warnings as errors.
  337. */
  338. void SetDeprecatedWarningsAsErrors(bool v);
  339. /** Display a message to the user. */
  340. void IssueMessage(
  341. cmake::MessageType t, std::string const& text,
  342. cmListFileBacktrace const& backtrace = cmListFileBacktrace()) const;
  343. ///! run the --build option
  344. int Build(const std::string& dir, const std::string& target,
  345. const std::string& config,
  346. const std::vector<std::string>& nativeOptions, bool clean);
  347. ///! run the --open option
  348. bool Open(const std::string& dir, bool dryRun);
  349. void UnwatchUnusedCli(const std::string& var);
  350. void WatchUnusedCli(const std::string& var);
  351. cmState* GetState() const { return this->State; }
  352. void SetCurrentSnapshot(cmStateSnapshot const& snapshot)
  353. {
  354. this->CurrentSnapshot = snapshot;
  355. }
  356. cmStateSnapshot GetCurrentSnapshot() const { return this->CurrentSnapshot; }
  357. protected:
  358. void RunCheckForUnusedVariables();
  359. void InitializeProperties();
  360. int HandleDeleteCacheVariables(const std::string& var);
  361. typedef std::vector<cmGlobalGeneratorFactory*> RegisteredGeneratorsVector;
  362. RegisteredGeneratorsVector Generators;
  363. typedef std::vector<cmExternalMakefileProjectGeneratorFactory*>
  364. RegisteredExtraGeneratorsVector;
  365. RegisteredExtraGeneratorsVector ExtraGenerators;
  366. void AddScriptingCommands();
  367. void AddProjectCommands();
  368. void AddDefaultGenerators();
  369. void AddDefaultExtraGenerators();
  370. cmGlobalGenerator* GlobalGenerator;
  371. std::map<std::string, DiagLevel> DiagLevels;
  372. std::string GeneratorInstance;
  373. std::string GeneratorPlatform;
  374. std::string GeneratorToolset;
  375. ///! read in a cmake list file to initialize the cache
  376. void ReadListFile(const std::vector<std::string>& args, const char* path);
  377. bool FindPackage(const std::vector<std::string>& args);
  378. ///! Check if CMAKE_CACHEFILE_DIR is set. If it is not, delete the log file.
  379. /// If it is set, truncate it to 50kb
  380. void TruncateOutputLog(const char* fname);
  381. /**
  382. * Method called to check build system integrity at build time.
  383. * Returns 1 if CMake should rerun and 0 otherwise.
  384. */
  385. int CheckBuildSystem();
  386. void SetDirectoriesFromFile(const char* arg);
  387. //! Make sure all commands are what they say they are and there is no
  388. /// macros.
  389. void CleanupCommandsAndMacros();
  390. void GenerateGraphViz(const char* fileName) const;
  391. cmVariableWatch* VariableWatch;
  392. private:
  393. ProgressCallbackType ProgressCallback;
  394. void* ProgressCallbackClientData;
  395. bool InTryCompile;
  396. WorkingMode CurrentWorkingMode;
  397. bool DebugOutput;
  398. bool Trace;
  399. bool TraceExpand;
  400. bool WarnUninitialized;
  401. bool WarnUnused;
  402. bool WarnUnusedCli;
  403. bool CheckSystemVars;
  404. std::map<std::string, bool> UsedCliVariables;
  405. std::string CMakeEditCommand;
  406. std::string CXXEnvironment;
  407. std::string CCEnvironment;
  408. std::string CheckBuildSystemArgument;
  409. std::string CheckStampFile;
  410. std::string CheckStampList;
  411. std::string VSSolutionFile;
  412. std::vector<std::string> SourceFileExtensions;
  413. std::vector<std::string> HeaderFileExtensions;
  414. bool ClearBuildSystem;
  415. bool DebugTryCompile;
  416. cmFileTimeComparison* FileComparison;
  417. std::string GraphVizFile;
  418. InstalledFilesMap InstalledFiles;
  419. cmState* State;
  420. cmStateSnapshot CurrentSnapshot;
  421. cmMessenger* Messenger;
  422. std::vector<std::string> TraceOnlyThisSources;
  423. void UpdateConversionPathTable();
  424. // Print a list of valid generators to stderr.
  425. void PrintGeneratorList();
  426. void CreateDefaultGlobalGenerator();
  427. /**
  428. * Convert a message type between a warning and an error, based on the state
  429. * of the error output CMake variables, in the cache.
  430. */
  431. cmake::MessageType ConvertMessageType(cmake::MessageType t) const;
  432. /*
  433. * Check if messages of this type should be output, based on the state of the
  434. * warning and error output CMake variables, in the cache.
  435. */
  436. bool IsMessageTypeVisible(cmake::MessageType t) const;
  437. };
  438. #define CMAKE_STANDARD_OPTIONS_TABLE \
  439. { "-C <initial-cache>", "Pre-load a script to populate the cache." }, \
  440. { "-D <var>[:<type>]=<value>", "Create a cmake cache entry." }, \
  441. { "-U <globbing_expr>", "Remove matching entries from CMake cache." }, \
  442. { "-G <generator-name>", "Specify a build system generator." }, \
  443. { "-T <toolset-name>", \
  444. "Specify toolset name if supported by generator." }, \
  445. { "-A <platform-name>", \
  446. "Specify platform name if supported by generator." }, \
  447. { "-Wdev", "Enable developer warnings." }, \
  448. { "-Wno-dev", "Suppress developer warnings." }, \
  449. { "-Werror=dev", "Make developer warnings errors." }, \
  450. { "-Wno-error=dev", "Make developer warnings not errors." }, \
  451. { "-Wdeprecated", "Enable deprecation warnings." }, \
  452. { "-Wno-deprecated", "Suppress deprecation warnings." }, \
  453. { "-Werror=deprecated", "Make deprecated macro and function warnings " \
  454. "errors." }, \
  455. { \
  456. "-Wno-error=deprecated", "Make deprecated macro and function warnings " \
  457. "not errors." \
  458. }
  459. #define FOR_EACH_C_FEATURE(F) \
  460. F(c_std_90) \
  461. F(c_std_99) \
  462. F(c_std_11) \
  463. F(c_function_prototypes) \
  464. F(c_restrict) \
  465. F(c_static_assert) \
  466. F(c_variadic_macros)
  467. #define FOR_EACH_CXX_FEATURE(F) \
  468. F(cxx_std_98) \
  469. F(cxx_std_11) \
  470. F(cxx_std_14) \
  471. F(cxx_std_17) \
  472. F(cxx_aggregate_default_initializers) \
  473. F(cxx_alias_templates) \
  474. F(cxx_alignas) \
  475. F(cxx_alignof) \
  476. F(cxx_attributes) \
  477. F(cxx_attribute_deprecated) \
  478. F(cxx_auto_type) \
  479. F(cxx_binary_literals) \
  480. F(cxx_constexpr) \
  481. F(cxx_contextual_conversions) \
  482. F(cxx_decltype) \
  483. F(cxx_decltype_auto) \
  484. F(cxx_decltype_incomplete_return_types) \
  485. F(cxx_default_function_template_args) \
  486. F(cxx_defaulted_functions) \
  487. F(cxx_defaulted_move_initializers) \
  488. F(cxx_delegating_constructors) \
  489. F(cxx_deleted_functions) \
  490. F(cxx_digit_separators) \
  491. F(cxx_enum_forward_declarations) \
  492. F(cxx_explicit_conversions) \
  493. F(cxx_extended_friend_declarations) \
  494. F(cxx_extern_templates) \
  495. F(cxx_final) \
  496. F(cxx_func_identifier) \
  497. F(cxx_generalized_initializers) \
  498. F(cxx_generic_lambdas) \
  499. F(cxx_inheriting_constructors) \
  500. F(cxx_inline_namespaces) \
  501. F(cxx_lambdas) \
  502. F(cxx_lambda_init_captures) \
  503. F(cxx_local_type_template_args) \
  504. F(cxx_long_long_type) \
  505. F(cxx_noexcept) \
  506. F(cxx_nonstatic_member_init) \
  507. F(cxx_nullptr) \
  508. F(cxx_override) \
  509. F(cxx_range_for) \
  510. F(cxx_raw_string_literals) \
  511. F(cxx_reference_qualified_functions) \
  512. F(cxx_relaxed_constexpr) \
  513. F(cxx_return_type_deduction) \
  514. F(cxx_right_angle_brackets) \
  515. F(cxx_rvalue_references) \
  516. F(cxx_sizeof_member) \
  517. F(cxx_static_assert) \
  518. F(cxx_strong_enums) \
  519. F(cxx_template_template_parameters) \
  520. F(cxx_thread_local) \
  521. F(cxx_trailing_return_types) \
  522. F(cxx_unicode_literals) \
  523. F(cxx_uniform_initialization) \
  524. F(cxx_unrestricted_unions) \
  525. F(cxx_user_literals) \
  526. F(cxx_variable_templates) \
  527. F(cxx_variadic_macros) \
  528. F(cxx_variadic_templates)
  529. #endif