Linux build with cmake

CMake Tutorial To Build and Compile In Linux

Binaries are created by building or compiling sources like C, C++, etc. In simple applications, we can build by using the compiler like GCC directly. But this is inconvenient if the application is big and has a lot of source code, configuration file, and build options. Developers generally prefer to build systems like make but there is an alternative named CMake which is popular in the Linux ecosystem too.

About cmake Command

CMake is an extensible and opensource build manage software.

cmake Installation

We can install CMake for different Linux distributions with the following commands.

Ubuntu, Debian, Mint, Kali

Fedora, CentOS, RHEL

Example Application

In order to compile an application, we need some source code. We will use the following source code which is written in C++ and have very basic logic. But as stated before CMake is designed to be used complex build processes.

cmake Global Variables

CMake is a very extensible and flexible build system where we can specify a lot of different options and variables. We will explain some of them below.

CMAKE_BINARY_DIR

This variable is used to specify the binary files directory which is generally same as CMAKE_SOURCE_DIR .

CMAKE_SOURCE_DIR

This variable is used to specify the source directory where the source code and other related configurations reside.

EXECUTABLE_OUTPUT_PATH

After the compile operation the created executable file will be written to the specified directory.

LIBRARY_OUTPUT_PATH

If we want to create libraries in a separate path we can use this variable where all created libraries will be put.

Источник

Get started with CMake Tools on Linux

CMake is an open-source, cross-platform tool that uses compiler and platform independent configuration files to generate native build tool files specific to your compiler and platform.

The CMake Tools extension integrates Visual Studio Code and CMake to make it easy to configure, build, and debug your C++ project.

In this tutorial, you’ll use the CMake Tools extension for Visual Studio Code to configure, build, and debug a simple C++ CMake project on Linux. Aside from installing CMake, your compiler, debugger, and build tools, the steps in this tutorial apply generally to how you’d use CMake on other platforms, like Windows.

If you have any trouble, please file an issue for this tutorial in the VS Code documentation repository.

Prerequisites

To complete this tutorial on Ubuntu, install the following:

C++ extension for VS Code. Install the C/C++ extension by searching for ‘c++’ in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).

CMake Tools extension for VS Code. Install the CMake Tools extension by searching for ‘CMake tools’ in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).

You’ll also need to install CMake, a compiler, a debugger, and build tools.

Ensure that CMake is installed

The VS Code CMake Tools extension does its work by using CMake installed on your system. For best results, use CMake version 3.15 or greater.

See if CMake is already installed on your system. Open a Terminal window and enter the following command:

To install CMake, or to get a later version if you don’t at least have version 3.15, see the instructions for your platform at Kitware APT Repository. Install version 3.15 or greater.

Читайте также:  What is linux swap disk

Ensure that development tools are installed

Although you’ll use VS Code to edit your source code, you’ll compile and debug the source code using the compiler, debugger, and build tools (such as make ) installed on your system.

For this tutorial on Ubuntu, we’ll use the GCC compiler, GDB to debug, and make to build the project. These tools are not installed by default on Ubuntu, so you need to install them. Fortunately, that’s easy.

Check if GCC is installed

To see if GCC is already installed on your system, open a Terminal window and enter the following command:

If GCC isn’t installed, run the following command from the Terminal window to update the Ubuntu package lists. An out-of-date Linux distribution can interfere with getting the latest packages.

Next, install the GNU compiler, make , and the GDB debugger with this command:

Create a CMake project

If you have an existing CMake project that already has a CMakeLists.txt file in the root directory, you can skip to Select a kit to configure your existing project.

Otherwise, create a folder for a new project. From the Terminal window, create an empty folder called cmakeQuickStart , navigate into it, and open VS Code in that folder by entering the following commands:

The code . command opens VS Code in the current working folder, which becomes your «workspace».

Create a CMake hello world project

The CMake Tools extension can create the files for a basic CMake project for you. Open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and run the CMake: Quick Start command:

Enter a project name. This will be written to CMakeLists.txt and a few initial source files.

Next, select Executable as the project type to create a basic source file ( main.cpp ) that includes a basic main() function.

Note: If you had wanted to create a basic source and header file, you would have selected Library instead. But for this tutorial, Executable will do. If you are prompted to configure IntelliSense for the folder, select Allow.

This creates a hello world CMake project containing main.cpp , CMakeLists.txt (which tells the CMake tools how to build your project), and a folder named build for your build files:

Select a kit

Before you can use the CMake Tools extension to build a project, you need to configure it to know about the compilers on your system. Do that by scanning for ‘kits’. A kit represents a toolchain, which is the compiler, linker, and other tools used to build your project. To scan for kits:

Open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and run CMake: Select a Kit. The extension will automatically scan for kits on your computer and create a list of compilers found on your system.

Select the compiler you want to use. For example, depending on the compilers you have installed, you might see something like:

Configure Hello World

There are two things you must do to configure your CMake project: select a kit (which you just did) and select a variant.

The kit you selected previously is shown in the Status bar. For example:

To change the kit, you can click on the kit in the Status bar, or run the CMake: Select a kit command again from the Command Palette. If you don’t see the compiler you’re looking for, you can edit the cmake-tools-kits.json file in your project. To edit the file, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and run the CMake: Edit User-Local CMake Kits command.

Select a variant

A variant contains instructions for how to build your project. By default, the CMake Tools extension provides four variants, each corresponding to a default build type: Debug , Release , MinRelSize , and RelWithDebInfo . These options do the following:

Читайте также:  Жесткий диск не создает разделы при установке windows

Debug : disables optimizations and includes debug info. Release : Includes optimizations but no debug info. MinRelSize : Optimizes for size. No debug info. RelWithDebInfo : Optimizes for speed and includes debug info.

To select a variant, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) run the CMake: Select Variant command.

Select Debug to include debug information with your build.

The selected variant will appear in the Status bar next to the active kit.

CMake: Configure

Now that you’ve selected a kit and a variant, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and run the CMake: Configure command to configure your project. This generates build files in the project’s build folder using the kit and variant you selected.

Build hello world

After configuring your project, you’re ready to build. Open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and run the CMake: Build command, or select the Build button from the Status bar.

You can select which targets you’d like to build by selecting CMake: Set Build Target from the Command Palette. By default, CMake Tools builds all targets. The selected target will appear in the Status bar next to the Build button.

Debug hello world

To run and debug your project, open main.cpp and put a breakpoint on the std::cout line. Then open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and run CMake: Debug. The debugger will stop on the std::cout line:

Go ahead and press F5 to continue.

You’ve now used the VS Code CMake Tools extension to use CMake to build and debug a C++ app on Ubuntu. The steps are the same for other platforms; the difference being how you install CMake and the compiler/debugger for the platform of your choice. For instructions on setting up compilers/debuggers for other platforms, see the following:

Источник

Введение в 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 не вызывает проблем, при этом тип библиотеки статическая\динамическая меняется лишь одним параметром.

Читайте также:  Windows 10 пропал микрофон не работает микрофон

Пример 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».
Примеры

Источник

Оцените статью