- How to Install the Latest Version of CMake on Ubuntu 16.04/18.04 Linux
- What is CMake?
- Installing CMake from Default Ubuntu Repo
- Installing CMake from PPA on Ubuntu 16.04
- Installing CMake from Binary Distrubtion
- Installing CMake from Source Code
- Installing CMake GUI
- Conclusion
- Введение в CMake
- Пример 1. Hello, World:
- Пример 2. Библиотеки:
- Пример 3. Подпроекты:
- Пример 4. Поиск библиотек:
- Пример 5. Внешние библиотеки и объектные файлы:
- Генераторы:
- Заключение:
- Installing CMake
- Windows
- macOS
- Linux, UNIX
- Download Verification
How to Install the Latest Version of CMake on Ubuntu 16.04/18.04 Linux
This post will guide you how to download and install the latest stable version of CMake on your Ubuntu Linux server. How do I install CMake tool from source code on Ubuntu Linux 16.04/18.04. How to install CMake from binary distrubtion on Ubuntu system.
What is CMake?
CMake is a cross-platform free and open-source software application for managing the build process of software using a compiler-independent method. It supports directory hierarchies and applications that depend on multiple libraries. CMake can be used to build, test, and package software on your system.
CMake can be used to control the software compilation process to geneate a native build environment that will compile source code, create libraries, generate wrappers and build executables in arbitray combinations.
Installing CMake from Default Ubuntu Repo
CMake package is available in the default Ubuntu 16.04 or 18.04 repository (it may be a older version of CMake), so you can use apt install command to install it directlry, type:
After installed, you can try to verify CMake version to check if it is successfully installed on your system, type:
From the above outputs you can see, the installed version of cmake is 3.10.2. You can go to the official download web page of CMake to see that the latest stable version of CMake is 3.13.4.
Installing CMake from PPA on Ubuntu 16.04
If you are using Ubuntu 16.04 system, you can also use a PPA repository to install CMake tool on your system with the following commands:
If CMake is alreay installed on your Ubuntu system, you can use apt upgrade command to upgrade CMake to the latest version, type:
Or you can add the following entries into /etc/apt/sources.list file:
Next, run the following command to update Package manager cache, type:
Then, install CMake tool using this PPA with the following command:
Installing CMake from Binary Distrubtion
You should know that the above two methods is not able to install the latest statble version (now the latest version is 3.13.4) of CMake. You can go to the official CMake webpage to download the latest version of CMake binary distrubtion file.
The Binary Distrubtion of CMake have two file extention, one is shell script, and another is archive file. The below will show you how to use those two files to install CMake.
For Shell Binary Distrubtion of CMake:
#1 Downloading CMake Bianary file with the following wget command:
#2 After intalled CMake Binary file, just execute it:
Note: you need to press y key on your keyboard to accept the license to continue the installation process. You also need to specify one target directory, if you type Y key, it will use the default setting to install CMake in the current directory.
#3 you need to change the current directory to ./cmake-3.13.4-Linux-x86_64/bin/, and all of CMake executables are located here.
For Archive Binary Distrubtion of CMake:
You can also install CMake from binary distrubtion its extention is tar.gz. You just need to download it to your local disk, and then extract all file to a specified direcotry.
#1 Download archive binary file of CMake with the following command:
#2 Extract all files from the above downloaded CMake archive binary file, type:
#3 changing the current directory to cmake-3.13.4-Linux-x86_64
#4 CMake executable will be in ./cmake-3.13.4-Linux-x86_64/bin/ directory.
#5 executing cmake script to check the current CMake version, type:
Installing CMake from Source Code
You can also compile the latest source code of CMake to install it. At this time, the latest stable version of CMake is 3.13.4. So you need to donwload the archive source code from the offical CMake web page, then compiling it. Just do the following steps:
#1 before downloading souce code, you need to unisntall the defualt older version of CMake by the default Ubuntu Package manager. Type:
#2 go to the official download page to get the latest version of CMake with the following wget command:
#3 extract all files from downloaded archive file, type:
#4 changing the current dirctory to cmake-3.13.4, type:
#5 compiling and install cmake with the following commands:
#6 checking CMake version to verify if it is installed successfully, type:
Installing CMake GUI
If you want to install CMake GUI on your Ubuntu system, you just need to use apt install command to install it, type:
Then you can use the following commands to check if CMake-gui package is installed normally:
You can run the cmake-gui command in Ubuntu terminal to launch the cmake gui, type:
Conclusion
You should know that how to install CMake tool on Ubuntu 16.04 or 18.04 from this guide, and you also know how to install CMake with the different methods on Ubuntu Linux server(default ubuntu repo, PPA, Source code). If you want to see more information about CMake, you can go the official web site of CMake directly.
Источник
Введение в CMake
CMake — кроcсплатформенная утилита для автоматической сборки программы из исходного кода. При этом сама CMake непосредственно сборкой не занимается, а представляет из себя front-end. В качестве back-end`a могут выступать различные версии make и Ninja. Так же CMake позволяет создавать проекты для CodeBlocks, Eclipse, KDevelop3, MS VC++ и Xcode. Стоит отметить, что большинство проектов создаются не нативных, а всё с теми же back-end`ами.
Для того что бы собрать проект средствами CMake, необходимо в корне дерева исходников разместить файл CMakeLists.txt, хранящий правила и цели сборки, и произвести несколько простых шагов.
Разберёмся на примерах.
Пример 1. Hello, World:
Синтаксис CMake похож на синтаксис bash, всё что после символа «#» является комментарием и обрабатываться программой не будет. CMake позволяет не засорять дерево исходных кодов временными файлами — очень просто и без лишних телодвижений сборка производится «Out-of-Source».
Создадим пустую директорию для временных файлов и перейдём туда.
$ mkdir tmp
fshp@panica-desktop:
$ cd tmp/
fshp@panica-desktop:
/cmake/example_1/
…
— Build files have been written to: /home/fshp/tmp
fshp@panica-desktop:
/tmp$ ls
CMakeCache.txt CMakeFiles cmake_install.cmake Makefile
fshp@panica-desktop:
/tmp$ make
Scanning dependencies of target main
[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o
Linking CXX executable main
[100%] Built target main
fshp@panica-desktop:
/tmp$ ./main
Hello, World!
fshp@panica-desktop:
Итак, наша программа собралась.
Папку tmp можно очищать\удалять без риска поломать исходники. Если CMakeLists.txt был изменен, то вызов make автоматически запустит cmake. Если исходники были перемещены, то нужно очистить временную директорию и запустить cmake вручную.
Пример 2. Библиотеки:
Переменные могут хранить списки значений, разделённых пробелами\табуляциями\переносами:
Оба варианта правильные
Что бы получить значение переменной ипользуем конструкцию:
Итак, эта версия нашего проекта включает в себя одну статическую библиотеку, собираемую из исходников. Если заменить «STATIC» на «SHARED», то получим библиотеку динамическую. Если тип библиотеки не указать, по умолчанию она соберётся как статическая.
При линковке указываются все необходимые библиотеки:
Как и при ручной компиляции, имена библиотек указываются без стандартного префикса «lib».
Итак, сборка библиотек с CMake не вызывает проблем, при этом тип библиотеки статическая\динамическая меняется лишь одним параметром.
Пример 3. Подпроекты:
В файле подпроекта ничего нового для вас нет. А вот в основном файле новые команды:
main.cpp мы не меняли, а foo.h перенесли. Команда указывает компилятору, где искать заголовочные файлы. Может быть вызвана несколько раз. Хидеры будут искаться во всех указаных директориях.
Указываем директорию с подпроектом, который будет собран как самостоятельный.
Вывод: проекты на CMake можно объединять в довольно сложные иерархические структуры, причем каждый подпроект в реальности является самостоятельным проектом, который в свою очередь может сам состоять из подпроектов. Это позволяет легко разбить вашу программу на необходимое количество отдельных модулей. Примером такого подхода может служить KDE.
Пример 4. Поиск библиотек:
CMake обладает достаточно развитыми средствами поиска установленых библиотек, правда они не встроеные, а реализованы в виде отдельных модулей. В стандартной поставке довольно много модулей, но некоторые проекты (например Ogre) поставляют свои. Они позволяют системе автоматически определить наличие необходимых для линковки проекта библиотек.
На debian модули располагаются в /usr/share/cmake-2.8/Modules/ (у вас версия может отличаться). За поиск библиотек отвечают модули, называющиеся FindNAME.cmake, где NAME — имя библиотеки.
Думаю, смысл должен быть понятен. Первый и второй блок — поиск библиотеки. Если в системе её нет, выведется сообщение об ошибке и завершается выполнение cmake. Третий блок похож, только он ищет не целый пакет библиотек, а лишь необходимый компонент. Каждый такой автоматизированый поиск определяет после выполнения как минимум 3 переменные:
SDL_FOUND, LIBXML2_FOUND, Boost_FOUND — признак присутствия бибилиотеки;
SDL_LIBRARY, LIBXML2_LIBRARIES, Boost_LIBRARIES — имена библиотек для линковки;
SDL_INCLUDE_DIR, LIBXML2_INCLUDE_DIR, Boost_INCLUDE_DIRS — пути к заголовочным файлам.
Если с первыми более или менее понятно, то вторые и третьи мне доставили много хлопот — половина имеет имена в единственном числе, половина — во множественном. Но оказалось, это легко отследить. В каждом модуле вначале есть коментарии, там описаны определяемые переменные. Посмотрите, например, /usr/share/cmake-2.8/Modules/FindLibXml2.cmake
Как видите, CMake способен сам определить наличие и местоположение необходимых библиотек и заголовочных файлов. В принципе, это должна уметь любая система автоматической сборки, иначе смысл в ней?
Пример 5. Внешние библиотеки и объектные файлы:
Если вы пишите для «дяди», а злой «дядя» любит самописные библиотеки и делиться исходниками не желает, поэтому присылает готовую библиотеку, то вы по адресу.
Объектные файлы в CMake стоят на ряду с исходниками — достаточно включить объектник в список файлов для компиляции.
С библиотеками потуже. Как известно, статическая библиотека это не что иное, как ar-архив, внутри которого лежат обычные объектники, никак не связаные между собой. Вы, наверное, уже догадались, как я поступал сначала. Да, просто потрошил библиотеку. Но потом был найден способ поэлегантнее:
Слово «IMPORTED», указывает, что библиотека берётся извне.
В CMake каждая цель имеет параметры, а set_property позволяет их изменять.
Линкуется такая библиотека стандартно:
Для динамических библиотек все аналогично, только тип «SHARED», расширение — «.so».
К сожалению, поддержка несистемных библиотек реализована немного костыльно. Возможно, я просто не знаю правильного варианта, поэтому буду рад, если «ткнете мордочкой». С другой стороны это не навороченый экзоскелет с системой жизнеобеспечения, а простейший костыль из двух строк.
Генераторы:
/cmake/example_3/ -G «KDevelop3 — Unix Makefiles»
Заключение:
Это не перевод мануала, а результат использования CMake в одном коммерческом проекте. Буду рад, если статья поможет хотя бы одному человеку — на русском языке подобной документации довольно мало.
Чем понравился CMake лично мне:
- один проект — один файл. Не нужно хранить кучу скриптов настройки, сборки и прочего хлама;
- Скорость работы в сравнении с autotools;
- простой и понятный синтаксис, конечно с элегантностью питона не потягаться, но и не брейнфак, в конце концов.;
- является front-end`ом для множества IDE;
- отображение прогресса — довольно удобно;
- цветной вывод — в серые будни немного краски не помешает;
Для Sublime Text есть плагин, добавляющий подсветку синтаксиса CMake, он так и называется — «CMake».
Примеры
Источник
Installing CMake
There are several ways to install CMake, depending on your platform.
Windows
There are pre-compiled binaries available on the Download page for Windows as MSI packages and ZIP files. The Windows installer has an option to modify the system PATH environment variable. If that is not selected during installation, one may manually add the install directory (e.g. C:\Program Files\CMake\bin) to the PATH in a command prompt.
One may alternatively download and build CMake from source. The Download page also provides source releases. In order to build CMake from a source tree on Windows, you must first install the latest binary version of CMake because it is used for building the source tree. Once the binary is installed, run it on CMake as you would any other project. Typically this means selecting CMake as the Source directory and then selecting a binary directory for the resulting executables.
macOS
There are pre-compiled binaries available on the Download page for macOS as disk images and tarballs. After copying CMake.app into /Applications (or a custom location), run it and follow the “How to Install For Command Line Use” menu item for instructions to make the command-line tools (e.g. cmake) available in the PATH. Or, one may manually add the install directory (e.g. /Applications/CMake.app/Contents/bin) to the PATH.
One may alternatively download and build CMake from source as in the following section.
Linux, UNIX
There are pre-compiled binaries available on the Download page for some UNIX platforms. One may alternatively download and build CMake from source. The Download page provides source releases. There are two possible approaches for building CMake from a source tree. If there is no existing CMake installation, a bootstrap script is provided:
(Note: the make install step is optional, cmake will run from the build directory.)
By default bootstrap will build CMake without any debug or optimization flags. To enable optimizations you will need to specify the CMAKE_BUILD_TYPE option to bootstrap like this: ./bootstrap — -DCMAKE_BUILD_TYPE:STRING=Release
For more options with bootstrap, run ./bootstrap —help .
Or, an existing CMake installation can be used to build a new version:
(Note: the make install step is optional, cmake will run from the build directory.) If you are not using the GNU C++ compiler, you need to tell the bootstrap script (or cmake) which compiler you want to use. This is done by setting the environment variables CC and CXX before running it. For example:
Download Verification
Each release on the Download page comes with a file named cmake-$version-SHA-256.txt, where $version is the release version number.
One may use this file to verify other downloads, such as the source tarball. For example:
The SHA-256 file itself can be verified by GPG signature:
The GPG key C6C265324BBEBDC350B513D02D2CEF1034921684 is a signing subkey whose expiry is updated yearly.
Источник