Cmake Ninja
CMake
install
Get the Software,下載對應平臺上的壓縮包即可。
eg. linux 平臺上用
測試
>cmake -version cmake version 3.21.1 CMake suite maintained and supported by Kitware (kitware.com/cmake).cmake 命令行的可配置參數如下
Usagecmake [options] <path-to-source>cmake [options] <path-to-existing-build>cmake [options] -S <path-to-source> -B <path-to-build>Specify a source directory to (re-)generate a build system for it in the current working directory. Specify an existing build directory to re-generate its build system.Options-S <path-to-source> = Explicitly specify a source directory.-B <path-to-build> = Explicitly specify a build directory.-C <initial-cache> = Pre-load a script to populate the cache.-D <var>[:<type>]=<value> = Create or update a cmake cache entry.-U <globbing_expr> = Remove matching entries from CMake cache.-G <generator-name> = Specify a build system generator.-T <toolset-name> = Specify toolset name if supported bygenerator.-A <platform-name> = Specify platform name if supported bygenerator.--toolchain <file> = Specify toolchain file[CMAKE_TOOLCHAIN_FILE].--install-prefix <directory> = Specify install directory[CMAKE_INSTALL_PREFIX].-Wdev = Enable developer warnings.-Wno-dev = Suppress developer warnings.-Werror=dev = Make developer warnings errors.-Wno-error=dev = Make developer warnings not errors.-Wdeprecated = Enable deprecation warnings.-Wno-deprecated = Suppress deprecation warnings.-Werror=deprecated = Make deprecated macro and function warningserrors.-Wno-error=deprecated = Make deprecated macro and function warningsnot errors.--preset <preset>,--preset=<preset>= Specify a configure preset.--list-presets = List available presets.-E = CMake command mode.-L[A][H] = List non-advanced cached variables.--build <dir> = Build a CMake-generated project binary tree.--install <dir> = Install a CMake-generated project binarytree.--open <dir> = Open generated project in the associatedapplication.-N = View mode only.-P <file> = Process script mode.--find-package = Legacy pkg-config like mode. Do not use.--graphviz=[file] = Generate graphviz of dependencies, seeCMakeGraphVizOptions.cmake for more.--system-information [file] = Dump information about this system.--log-level=<ERROR|WARNING|NOTICE|STATUS|VERBOSE|DEBUG|TRACE>= Set the verbosity of messages from CMakefiles. --loglevel is also accepted forbackward compatibility reasons.--log-context = Prepend log messages with context, if given--debug-trycompile = Do not delete the try_compile build tree.Only useful on one try_compile at a time.--debug-output = Put cmake in a debug mode.--debug-find = Put cmake find in a debug mode.--trace = Put cmake in trace mode.--trace-expand = Put cmake in trace mode with variableexpansion.--trace-format=<human|json-v1>= Set the output format of the trace.--trace-source=<file> = Trace only this CMake file/module. Multipleoptions allowed.--trace-redirect=<file> = Redirect trace output to a file instead ofstderr.--warn-uninitialized = Warn about uninitialized values.--no-warn-unused-cli = Don't warn about command line options.--check-system-vars = Find problems with variable usage in systemfiles.--profiling-format=<fmt> = Output data for profiling CMake scripts.Supported formats: google-trace--profiling-output=<file> = Select an output path for the profiling dataenabled through --profiling-format.--help,-help,-usage,-h,-H,/? = Print usage information and exit.--version,-version,/V [<f>] = Print version number and exit.--help-full [<f>] = Print all help manuals and exit.--help-manual <man> [<f>] = Print one help manual and exit.--help-manual-list [<f>] = List help manuals available and exit.--help-command <cmd> [<f>] = Print help for one command and exit.--help-command-list [<f>] = List commands with help available and exit.--help-commands [<f>] = Print cmake-commands manual and exit.--help-module <mod> [<f>] = Print help for one module and exit.--help-module-list [<f>] = List modules with help available and exit.--help-modules [<f>] = Print cmake-modules manual and exit.--help-policy <cmp> [<f>] = Print help for one policy and exit.--help-policy-list [<f>] = List policies with help available and exit.--help-policies [<f>] = Print cmake-policies manual and exit.--help-property <prop> [<f>] = Print help for one property and exit.--help-property-list [<f>] = List properties with help available andexit.--help-properties [<f>] = Print cmake-properties manual and exit.--help-variable var [<f>] = Print help for one variable and exit.--help-variable-list [<f>] = List variables with help available and exit.--help-variables [<f>] = Print cmake-variables manual and exit.GeneratorsThe following generators are available on this platform (* marks default):Green Hills MULTI = Generates Green Hills MULTI files(experimental, work-in-progress). * Unix Makefiles = Generates standard UNIX makefiles.Ninja = Generates build.ninja files.Ninja Multi-Config = Generates build-<Config>.ninja files.Watcom WMake = Generates Watcom WMake makefiles.CodeBlocks - Ninja = Generates CodeBlocks project files.CodeBlocks - Unix Makefiles = Generates CodeBlocks project files.CodeLite - Ninja = Generates CodeLite project files.CodeLite - Unix Makefiles = Generates CodeLite project files.Eclipse CDT4 - Ninja = Generates Eclipse CDT 4.0 project files.Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.Kate - Ninja = Generates Kate project files.Kate - Unix Makefiles = Generates Kate project files.Sublime Text 2 - Ninja = Generates Sublime Text 2 project files.Sublime Text 2 - Unix Makefiles= Generates Sublime Text 2 project files.其中Generators是生成器,實際上cmake 的作用就是生成一個makefile(或者其他類型的最終編譯文件(eg:build.ninja)),默認情況下,使用的生成器是Unix Makefiles,最終生成makefile文件,然后通過make 命令可以看是編譯,但這個參數如上,可以通過-G 來指定。
搭建項目
CMake Tutorial
source code
source code
解壓后,可以在cmake-3.22.1/Help/guide/tutorial/路徑下找到官方的示例文件,再跟著Tutorial學就好了
Step1
cmake入門,初步編譯一個文件
. ├── CMakeLists.txt ├── TutorialConfig.h.in ├── build │ ├── CMakeCache.txt │ ├── CMakeFiles │ ├── Makefile │ ├── Tutorial │ ├── TutorialConfig.h │ └── cmake_install.cmake └── tutorial.cxxbuild 文件夾自己創建一個,也可以不創建,只是為了方便區分。
相關文件內容如下
CMakeLists.txt
tutorial.cxx
// A simple program that computes the square root of a number #include <cmath> #include <iostream> #include <string> #include "TutorialConfig.h"int main(int argc, char* argv[]) {if (argc < 2) {// report versionstd::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."<< Tutorial_VERSION_MINOR << std::endl;std::cout << "Usage: " << argv[0] << " number" << std::endl;return 1;}// convert input to doubleconst double inputValue = atof(argv[1]);// calculate square rootconst double outputValue = sqrt(inputValue);std::cout << "The square root of " << inputValue << " is " << outputValue<< std::endl;return 0; }TutorialConfig.h.in
// the configured options and settings for Tutorial #define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@ #define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@編譯方式是cd到build,使用cmake ../命令后,沒有報錯再使用make
可以看到cmake命令需要跟CMakeLists.txt文件在同一個位置下使用,也是使用…/的原因,如果沒有創建build文件夾,直接使用cmake 即可
Step2
主要是鏈接外部文件和動態配置
. ├── CMakeLists.txt ├── MathFunctions │ ├── CMakeLists.txt │ ├── MathFunctions.h │ └── mysqrt.cxx ├── TutorialConfig.h.in ├── build │ ├── CMakeCache.txt │ ├── CMakeFiles │ ├── Makefile │ ├── MathFunctions │ ├── TutorialConfig.h │ └── cmake_install.cmake └── tutorial.cxx結構圖的build目錄內容可以忽略,執行cmake后自然會生成
按照官方的代碼,最后修改的文件示例和注釋如下
CMakeLists.txt
tutorial.cxx
// A simple program that computes the square root of a number #include <cmath> #include <iostream> #include <string>#include "TutorialConfig.h"//判斷是否配置了開關,有就include #ifdef USE_MYMATH # include "MathFunctions.h" #endifint main(int argc, char* argv[]) {if (argc < 2) {// report versionstd::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."<< Tutorial_VERSION_MINOR << std::endl;std::cout << "Usage: " << argv[0] << " number" << std::endl;return 1;}// convert input to doubleconst double inputValue = std::stod(argv[1]);//判斷是否配置開關,有就用鏈接庫提供的函數實現,沒有就用cpp提供的默認實現sqrt()#ifdef USE_MYMATHconst double outputValue = mysqrt(inputValue);#elseconst double outputValue = sqrt(inputValue);#endifstd::cout << "The square root of " << inputValue << " is " << outputValue<< std::endl;return 0; }TutorialConfig.h.in
// the configured options and settings for Tutorial #define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@ #define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@ #cmakedefine USE_MYMATH //用于引入命令行設置(eg:cmake ../ -DUSE_MYMATH=ON 開啟mymath)其中工具庫放在 MathFunctions
里面的文件沒什么變化,但需要自己增加一個CMakeLists.txt,內容為
重點
與上一章的編譯方式不同,這次編譯需要帶上參數cmake ../ -DUSE_MYMATH=ON,設置OFF/ON可以對應配置是否使用外置文件,默認使用cmake的參數是ON
Step3
使用一些外部文件,在Step2中,總是要在最外層的配置文件(CMakeLists.txt)中添加 ${EXTRA_INCLUDES},cmake 可以使用諸如
target_compile_definitions()
target_compile_options()
target_include_directories()
target_link_libraries()
來做好被鏈接模塊與main之間的編譯關系。
相對于使用Step 2的代碼,只需要在MathFunctions/CMakeLists.txt
中增加
就可以把需要的鏈接文件鏈接到main 的source 路徑上
此時就可以刪除工程下CMakeLists.txt文件中的
和
target_include_directories(Tutorial PUBLIC"${PROJECT_BINARY_DIR}"${EXTRA_INCLUDES})中的 ${EXTRA_INCLUDES}
在完成修改后按照Step2中的build flow即可實現同樣的效果。
Step 4
關于instal和test
install
在編譯結束后,可以install到平臺上或者指定位置,這個操作相當于將關聯文件打包并放在平臺的某個位置
對于cmake 項目,只需要在有關聯到的文件的CMakeLists.txt 中增加
即可保存相關的lib文件和.h文件。使用Step3的示例,則是要在
最上層CMakeLists.txt中增加
在MathFunctions/CMakeLists.txt末尾增加
install(TARGETS Tutorial DESTINATION bin) install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"DESTINATION include)然后回到/build 做
cmake ../ make install默認情況下,make install 位置在/usr/local ,可以通過增加配置指定make install DESTDIR=/home/chen/output
運行后對應位置的tree為
test
稍微看了一下,包含一些cmake的語法,就不深入了,上面的示例,需要測試的話,只需要在頂層CMakeLists.txt中末尾添加如下
enable_testing()# does the application run add_test(NAME Runs COMMAND Tutorial 25)# does the usage message work? add_test(NAME Usage COMMAND Tutorial) set_tests_properties(UsagePROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number")# define a function to simplify adding tests function(do_test target arg result)add_test(NAME Comp${arg} COMMAND ${target} ${arg})set_tests_properties(Comp${arg}PROPERTIES PASS_REGULAR_EXPRESSION ${result}) endfunction()# do a bunch of result based tests do_test(Tutorial 4 "4 is 2") do_test(Tutorial 9 "9 is 3") do_test(Tutorial 5 "5 is 2.236") do_test(Tutorial 7 "7 is 2.645") do_test(Tutorial 25 "25 is 5") do_test(Tutorial -25 "-25 is (-nan|nan|0)") do_test(Tutorial 0.0001 "0.0001 is 0.01")在/build 里面cmake ../ ;make;make test;
官網對這份測試的描述是
The first test simply verifies that the application runs, does not segfault or otherwise crash, and has a zero return value. This is the basic form of a CTest test.The next test makes use of the PASS_REGULAR_EXPRESSION test property to verify that the output of the test contains certain strings. In this case, verifying that the usage message is printed when an incorrect number of arguments are provided.Lastly, we have a function called do_test that runs the application and verifies that the computed square root is correct for given input. For each invocation of do_test, another test is added to the project with a name, input, and expected results based on the passed arguments.單元測試用到了再學吧
Step7
Packaging an Installer
Step11
Adding Export Configuration
Ninja
install
ubuntu:sudo apt install ninja-build
version:ninja --version
官網
Ninja實際使用上類似與makefile,也是構建文件關系,編譯相關的文件生成最終的執行文件
項目構建
CMake
在cmake項目中,可以直接使用ninja工具來加速編譯速度。
使用Cmake Step3 的示例
項目結構為
如前述,這部分主要增加自定義參數,來調節是否編譯用戶自己的庫(USE_MYMATH)。
這里,我們用ninja 來進行編譯。
cmake -B build -G Ninja -D USE_MYMATH=OFF
參考cmake 章節,上述的定義參數分別代表
-B = Explicitly specify a build directory.
-G = Specify a build system generator.
-D [:]= = Create or update a cmake cache entry.
運行指令后會生成build 目錄,并在該目錄下生成build.ninja文件(相當于makefile),同時傳遞了USE_MYMATH=OFF這個參數到配置中
注意: Ninja 不是用來替代cmake 的,它是作為cmake生成器的一部分,可選地參與cmake 構建
此時只需要再build目錄下運行ninja即可完成編譯。
ninja 編譯過程只會打印一句log(官方認為這讓用戶感覺到快😂),一個好的特性是可以生成編譯關系圖,只需要使用
ninja -t graph all |dot -T png -o graph.png(需要安裝graphviz=>apt install graphviz)
實際上只要有build.ninja 文件,即可運行ninja
編寫自己的ninja 項目
前述,ninja 實際上是和make(makefile)做對比的,可以理解為ninja 是makefile的并行高速精簡版本,編譯速度比make 快。
我稍微看了語法,和make 差別不大,一個項目如下
其中
build.ninja
foo.c
#include <stdio.h>int main(int argc, char *argv[]) {printf("sandeepin poi!");return 0; }創建這兩個文件后直接運行ninja即可,和前文類似,也可以生成graph。
這是簡單不過的一個示例了,可以看到build.ninja 文件中只是創建了編譯規則 rule cc 并在build 命令中傳遞編譯文件和輸入文件。這和makefile很類似。當然ninja 還有更多特性,比如利用縮進(shadowed)來覆蓋某條規則可能會使用的參數,類似于全局變量和局部變量。其他特性就不展開了。
參考官網,國內轉譯
其他參考1
其他參考2
Cmake 語法與實戰入門
總結
以上是生活随笔為你收集整理的Cmake Ninja的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Intellij IDEA常用快捷键一览
- 下一篇: 1688店铺所有商品API接口、店铺列表