что такое install directory
From MozillaZine Knowledge Base
The installation directory is the directory where a Mozilla application stores its program files. It is usually a directory on your own computer. This applies to all Mozilla applications, including Firefox, Thunderbird, Mozilla Suite and SeaMonkey.
The installation directory is also known by the terms «program directory», «application directory», «program folder», and similar phrases.
Important: The installation directory does not include your preference settings or user data such as passwords, cookies, bookmarks or address books. That information is normally stored in the profile folder for your Mozilla application, in a separate location.
Contents
Finding the installation directory
If you can start a Mozilla application by using a shortcut or launcher icon, then you can usually see where its installation directory is located by context-clicking (right-clicking) the icon and looking at the properties.
The following sections give examples of the default installation directory for various operating systems and applications. The actual directory on your system might not be the default if you chose a different installation directory when you installed the application.
If you cannot find the installation directory in either of these ways, then you can try searching your computer’s file system. The following sections also give examples of names to search for.
Windows
Examples of default installation directories:
Firefox | C:\Program Files\Mozilla Firefox\ |
Firefox (64-bit Windows) | C:\Program Files (x86)\Mozilla Firefox\ |
Thunderbird | C:\Program Files\Mozilla Thunderbird\ |
Mozilla Suite | C:\Program Files\mozilla.org\Mozilla\ |
SeaMonkey 1.x | C:\Program Files\mozilla.org\SeaMonkey\ |
SeaMonkey 2.0 | C:\Program Files\SeaMonkey\ |
Example search for Firefox: firefox.exe
Linux
Examples of default installation directories (32-bit Linux):
Firefox | /usr/lib/firefox- For example, if using Firefox 1.0: /usr/lib/firefox-1.0 |
Mozilla Suite | /usr/lib/mozilla- For example: /usr/lib/mozilla-1.7.3 |
Examples of default installation directories (64-bit Linux):
Firefox | /usr/lib64/firefox- For example: /usr/lib64/firefox-3.0.9 |
Thunderbird | /usr/lib64/thunderbird- For example: /usr/lib64/thunderbird-2.0.0.21 |
The installation directory path may vary depending on the distribution if you use a package manager to install the application from their repository.
Example search for Firefox (searching from / ): firefox
Mac OS X
Examples of default installation directories (folders):
Firefox | /Applications/Firefox.app |
Thunderbird | /Applications/Thunderbird.app |
Mozilla Suite | /Applications/Mozilla.app |
To open one of these folders, Ctrl-click it and select Show Package Contents. If you simply click it, you will start the application.
Полное руководство по CMake. Часть вторая: Система сборки
Введение
В данной статье рассмотрено использование системы сборки CMake, применяемой в колоссальном количестве проектов на C/C++. Строго рекомендуется прочитать первую часть руководства во избежание непонимания синтаксиса языка CMake, явным образом фигурирующего на протяжении всей статьи.
Запуск CMake
Ниже приведены примеры использования языка CMake, по которым Вам следует попрактиковаться. Экспериментируйте с исходным кодом, меняя существующие команды и добавляя новые. Чтобы запустить данные примеры, установите CMake с официального сайта.
Принцип работы
Система сборки CMake представляет из себя оболочку над другими платформенно зависимыми утилитами (например, Ninja или Make). Таким образом, в самом процессе сборки, как бы парадоксально это ни звучало, она непосредственного участия не принимает.
Система сборки CMake принимает на вход файл CMakeLists.txt с описанием правил сборки на формальном языке CMake, а затем генерирует промежуточные и нативные файлы сборки в том же каталоге, принятых на Вашей платформе.
Сгенерированные файлы будут содержать конкретные названия системных утилит, директорий и компиляторов, в то время как команды CMake орудуют лишь абстрактным понятием компилятора и не привязаны к платформенно зависимым инструментам, сильно различающихся на разных операционных системах.
Проверка версии CMake
Команда cmake_minimum_required проверяет запущенную версию CMake: если она меньше указанного минимума, то CMake завершает свою работу фатальной ошибкой. Пример, демонстрирующий типичное использование данной команды в начале любого CMake-файла:
Как подметили в комментариях, команда cmake_minimum_required выставляет все флаги совместимости (смотреть cmake_policy ). Некоторые разработчики намеренно выставляют низкую версию CMake, а затем корректируют функционал вручную. Это позволяет одновременно поддерживать древние версии CMake и местами использовать новые возможности.
Оформление проекта
В начале любого CMakeLists.txt следует задать характеристики проекта командой project для лучшего оформления интегрированными средами и прочими инструментами разработки.
Запуск скриптовых файлов
Команда include заменяет строку своего вызова кодом заданного файла, действуя аналогично препроцессорной команде include языков C/C++. Этот пример запускает скриптовый файл MyCMakeScript.cmake описанной командой:
Компиляция исполняемых файлов
Компиляция библиотек
Добавление исходников к цели
Повторяющиеся вызовы команды target_sources добавляют исходные файлы к цели в том порядке, в каком они были вызваны, поэтому нижние два блока кода являются функционально эквивалентными:
Генерируемые файлы
Важно подметить, что «DLL-платформами» считаются все платформы, основанные на Windows, в том числе и Cygwin.
Компоновка с библиотеками
Стоит отметить, что модульные библиотеки не подлежат компоновке с исполняемыми файлами или другими библиотеками, так как они предназначены исключительно для загрузки техниками выполнения.
Работа с целями
Как упомянули в комментариях, цели в CMake тоже подвержены ручному манипулированию, однако весьма ограниченному.
Имеется возможность управления свойствами целей, предназначенных для задания процесса сборки проекта. Команда get_target_property присваивает предоставленной переменной значение свойства цели. Данный пример выводит значение свойства C_STANDARD цели MyTarget на экран:
Пример выше задал цели MyTarget свойства, влияющие на процесс компиляции, а именно: при компиляции цели MyTarget CMake затребует компилятора о использовании стандарта C11. Все известные именования свойств целей перечисляются на этой странице.
Также имеется возможность проверки ранее определённых целей с помощью конструкции if(TARGET ) :
Добавление подпроектов
Команда add_subdirectory побуждает CMake к незамедлительной обработке указанного файла подпроекта. Пример ниже демонстрирует применение описанного механизма:
Стоит отметить, что все переменные из родительской области видимости унаследуются добавленным каталогом, а все переменные, определённые и переопределённые в данном каталоге, будут видимы лишь ему (если ключевое слово PARENT_SCOPE не было определено аргументом команды set ). Данную особенность упомянули в комментариях к предыдущей статье.
Поиск пакетов
Команда find_package находит и загружает настройки внешнего проекта. В большинстве случаев она применяется для последующей линковки внешних библиотек, таких как Boost и GSL. Данный пример вызывает описанную команду для поиска библиотеки GSL и последующей линковки:
В общем случае, команда find_package имеет две разновидности запуска: модульную и конфигурационную. Пример выше применял модульную форму. Это означает, что во время вызова команды CMake ищет скриптовый файл вида Find
Способы включения заголовков
Команда target_include_directories влияет лишь на указанную первым аргументом цель, а на другие цели никакого воздействия не оказывается. Пример ниже демонстрирует разницу между этими двумя командами:
Установка проекта
Команда install генерирует установочные правила для Вашего проекта. Данная команда способна работать с целями, файлами, папками и многим другим. Сперва рассмотрим установку целей.
После завершения обработки CMake всех Ваших файлов Вы можете выполнить установку всех описанных объектов командой sudo checkinstall (если CMake генерирует Makefile ), или же выполнить данное действие интегрированной средой разработки, поддерживающей CMake.
Наглядный пример проекта
Данное руководство было бы неполным без демонстрации реального примера использования системы сборки CMake. Рассмотрим схему простого проекта, использующего CMake в качестве единственной системы сборки:
Заключение
Теперь Вы способны писать свои и понимать чужие CMake-файлы, а подробно прочитать про остальные механизмы Вы можете на официальном сайте.
Следующая статья данного руководства будет посвящена тестированию и созданию пакетов с помощью CMake и выйдет через неделю. До скорых встреч!
installВ¶
Specify rules to run at install time.
SynopsisВ¶
IntroductionВ¶
This command generates installation rules for a project. Install rules specified by calls to the install() command within a source directory are executed in order during installation.
Changed in version 3.14: Install rules in subdirectories added by calls to the add_subdirectory() command are interleaved with those in the parent directory to run in the order declared (see policy CMP0082 ).
There are multiple signatures for this command. Some of them define installation options for files and targets. Options common to multiple signatures are covered here but they are valid only for signatures that specify them. The common options are:
Specify the directory on disk to which a file will be installed. Arguments can be relative or absolute paths.
If a relative path is given it is interpreted relative to the value of the CMAKE_INSTALL_PREFIX variable. The prefix can be relocated at install time using the DESTDIR mechanism explained in the CMAKE_INSTALL_PREFIX variable documentation.
If an absolute path (with a leading slash or drive letter) is given it is used verbatim.
As absolute paths are not supported by cpack installer generators, it is preferable to use relative paths throughout. In particular, there is no need to make paths absolute by prepending CMAKE_INSTALL_PREFIX ; this prefix is used by default if the DESTINATION is a relative path.
Specify a list of build configurations for which the install rule applies (Debug, Release, etc.). Note that the values specified for this option only apply to options listed AFTER the CONFIGURATIONS option. For example, to set separate install paths for the Debug and Release configurations, do the following:
Specify that the file is excluded from a full installation and only installed as part of a component-specific installation
Specify a name for an installed file that may be different from the original file. Renaming is allowed only when a single file is installed by the command.
Specify that it is not an error if the file to be installed does not exist.
New in version 3.1: Command signatures that install files may print messages during installation. Use the CMAKE_INSTALL_MESSAGE variable to control which messages are printed.
New in version 3.11: Many of the install() variants implicitly create the directories containing the installed files. If CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS is set, these directories will be created with the permissions specified. Otherwise, they will be created according to the uname rules on Unix-like platforms. Windows platforms are unaffected.
Installing TargetsВ¶
The TARGETS form specifies rules for installing targets from a project. There are several kinds of target Output Artifacts that may be installed:
Target artifacts of this kind include:
On AIX, the linker import file created for executables with ENABLE_EXPORTS enabled.
Target artifacts of this kind include:
Shared libraries, except
on macOS when marked as FRAMEWORK (see below).
Target artifacts of this kind include:
DLLs (on all Windows-based systems including Cygwin; note that the accompanying import libraries are of kind ARCHIVE ).
Object files associated with object libraries.
Both static and shared libraries marked with the FRAMEWORK property are treated as FRAMEWORK targets on macOS.
Executables marked with the MACOSX_BUNDLE property are treated as BUNDLE targets on macOS.
Any PUBLIC_HEADER files associated with a library are installed in the destination specified by the PUBLIC_HEADER argument on non-Apple platforms. Rules defined by this argument are ignored for FRAMEWORK libraries on Apple platforms because the associated files are installed into the appropriate locations inside the framework folder. See PUBLIC_HEADER for details.
For each of these arguments given, the arguments following them only apply to the target or file type specified in the argument. If none is given, the installation properties apply to all target types. If only one is given then only targets of that type will be installed (which can be used to install just a DLL or just an import library.)
The following table shows the target types with their associated variables and built-in defaults that apply when no destination is given:
Projects wishing to follow the common practice of installing headers into a project-specific subdirectory will need to provide a destination rather than rely on the above.
In addition to the common options listed above, each target can accept the following additional arguments:
New in version 3.12.
On some platforms a versioned shared library has a symbolic link such as:
Consider the following example:
In this scenario, if you choose to install only the Development component, both the headers and namelink will be installed without the library. (If you don’t also install the Libraries component, the namelink will be a dangling symlink, and projects that link to the library will have build errors.) If you install only the Libraries component, only the library will be installed, without the headers and namelink.
This option is typically used for package managers that have separate runtime and development packages. For example, on Debian systems, the library is expected to be in the runtime package, and the headers and namelink are expected to be in the development package.
See the VERSION and SOVERSION target properties for details on creating versioned shared libraries.
This option causes the installation of only the namelink when a library target is installed. On platforms where versioned shared libraries do not have namelinks or when a library is not versioned, the NAMELINK_ONLY option installs nothing. It is an error to use this parameter outside of a LIBRARY block.
When NAMELINK_ONLY is given, either NAMELINK_COMPONENT or COMPONENT may be used to specify the installation component of the namelink, but COMPONENT should generally be preferred.
The install(TARGETS) command can also accept the following options at the top level:
New in version 3.21.
This option causes all runtime dependencies of installed executable, shared library, and module targets to be added to the specified runtime dependency set. This set can then be installed with an install(RUNTIME_DEPENDENCY_SET) command.
This keyword and the RUNTIME_DEPENDENCIES keyword are mutually exclusive.
New in version 3.21.
RUNTIME_DEPENDENCIES is semantically equivalent to the following pair of calls:
where will be a randomly generated set name. The args. may include any of the following keywords supported by the install(RUNTIME_DEPENDENCY_SET) command:
The RUNTIME_DEPENDENCIES and RUNTIME_DEPENDENCY_SET keywords are mutually exclusive.
will install myExe to
The RUNTIME_DEPENDENCY_SET option causes the runtime artifacts of the imported executable, shared library, and module library targets to be added to the runtime dependency set. This set can then be installed with an install(RUNTIME_DEPENDENCY_SET) command.
Installing FilesВ¶
Projects wishing to follow the common practice of installing headers into a project-specific subdirectory will need to provide a destination rather than rely on the above.
Note that some of the types’ built-in defaults use the DATAROOT directory as a prefix. The DATAROOT prefix is calculated similarly to the types, with CMAKE_INSTALL_DATAROOTDIR as the variable and share as the built-in default. You cannot use DATAROOT as a TYPE parameter; please use DATA instead.
Installing DirectoriesВ¶
The DIRECTORY form installs contents of one or more directories to a given destination. The directory structure is copied verbatim to the destination. The last component of each directory name is appended to the destination directory but a trailing slash may be used to avoid this because it leaves the last component empty. Directory names given as relative paths are interpreted with respect to the current source directory. If no input directory names are given the destination directory will be created but nothing will be installed into it. The FILE_PERMISSIONS and DIRECTORY_PERMISSIONS options specify permissions given to files and directories in the destination. If USE_SOURCE_PERMISSIONS is specified and FILE_PERMISSIONS is not, file permissions will be copied from the source directory structure. If no permissions are specified files will be given the default permissions specified in the FILES form of the command, and the directories will be given the default permissions specified in the PROGRAMS form of the command.
New in version 3.1: The MESSAGE_NEVER option disables file installation status output.
will extract and install header files from a source tree.
Some options may follow a PATTERN or REGEX expression as described under string(REGEX) and are applied only to files or directories matching them. The EXCLUDE option will skip the matched file or directory. The PERMISSIONS option overrides the permissions setting for the matched file or directory. For example the code
Note that some of the types’ built-in defaults use the DATAROOT directory as a prefix. The DATAROOT prefix is calculated similarly to the types, with CMAKE_INSTALL_DATAROOTDIR as the variable and share as the built-in default. You cannot use DATAROOT as a TYPE parameter; please use DATA instead.
New in version 3.5: The list of dirs. given to DIRECTORY may use «generator expressions» too.
Custom Installation LogicВ¶
The SCRIPT form will invoke the given CMake script files during installation. If the script file name is a relative path it will be interpreted with respect to the current source directory. The CODE form will invoke the given CMake code during installation. Code is specified as a single argument inside a double-quoted string. For example, the code
will print a message during installation.
New in version 3.21: When the ALL_COMPONENTS option is given, the custom installation script code will be executed for every component of a component-specific installation. This option is mutually exclusive with the COMPONENT option.
Installing ExportsВ¶
-config.cmake file or the latter may be incorrectly matched by the glob and loaded.
New in version 3.7: In addition to cmake language files, the EXPORT_ANDROID_MK mode maybe used to specify an export to the android ndk build system. This mode accepts the same options as the normal export mode. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags and defines required to use the libraries.
The EXPORT form is useful to help outside projects use targets built and installed by the current project. For example, the code
will install the executable myexe to
Installs a runtime dependency set previously created by one or more install(TARGETS) or install(IMPORTED_RUNTIME_ARTIFACTS) commands. The dependencies of targets belonging to a runtime dependency set are installed in the RUNTIME destination and component on DLL platforms, and in the LIBRARY destination and component on non-DLL platforms. macOS frameworks are installed in the FRAMEWORK destination and component. Targets built within the build tree will never be installed as runtime dependencies, nor will their own dependencies, unless the targets themselves are installed with install(TARGETS).
CMake и C++ — братья навек
В процессе разработки я люблю менять компиляторы, режимы сборки, версии зависимостей, производить статический анализ, замерять производительность, собирать покрытие, генерировать документацию и т.д. И очень люблю CMake, потому что он позволяет мне делать всё то, что я хочу.
Многие ругают CMake, и часто заслуженно, но если разобраться, то не всё так плохо, а в последнее время очень даже неплохо, и направление развития вполне позитивное.
В данной заметке я хочу рассказать, как достаточно просто организовать заголовочную библиотеку на языке C++ в системе CMake, чтобы получить следующую функциональность:
Кто и так разбирается в плюсах и си-мейке может просто скачать шаблон проекта и начать им пользоваться.
Содержание
Проект изнутри
Структура проекта
Главным образом речь пойдёт о том, как организовать CMake-скрипты, поэтому они будут разобраны подробно. Остальные файлы каждый желающий может посмотреть непосредственно на странице проекта-шаблона.
Главный CMake-файл (./CMakeLists.txt)
Информация о проекте
В первую очередь нужно затребовать нужную версию системы CMake. CMake развивается, меняются сигнатуры команд, поведение в разных условиях. Чтобы CMake сразу понимал, чего мы от него хотим, нужно сразу зафиксировать наши к нему требования.
Затем обозначим наш проект, его название, версию, используемые языки и прочее (см. команду project ).
В данном случае указываем язык CXX (а это значит C++), чтобы CMake не напрягался и не искал компилятор языка C (по умолчанию в CMake включены два языка: C и C++).
Здесь же можно сразу проверить, включён ли наш проект в другой проект в качестве подпроекта. Это сильно поможет в дальнейшем.
Опции проекта
Предусмотрим две опции.
Первая опция — MYLIB_TESTING — для выключения модульных тестов. Это может понадобиться, если мы уверены, что с тестами всё в порядке, а мы хотим, например, только установить или запакетировать наш проект. Или наш проект включён в качестве подпроекта — в этом случае пользователю нашего проекта не интересно запускать наши тесты. Вы же не тестируете зависимости, которыми пользуетесь?
Кроме того, мы сделаем отдельную опцию MYLIB_COVERAGE для замеров покрытия кода тестами, но она потребует дополнительных инструментов, поэтому включать её нужно будет явно.
Опции компиляции
Разумеется, мы крутые программисты-плюсовики, поэтому хотим от компилятора максимального уровня диагностик времени компиляции. Ни одна мышь не проскочит.
Расширения тоже отключим, чтобы полностью соответствовать стандарту языка C++. По умолчанию в CMake они включены.
Основная цель
Наша библиотека состоит только из заголовочных файлов, а значит, мы не располагаем каким-либо выхлопом в виде статических или динамических библиотек. С другой стороны, чтобы использовать нашу библиотеку снаружи, её нужно установить, нужно, чтобы её можно было обнаружить в системе и подключить к своему проекту, и при этом вместе с ней были привязаны эти самые заголовки, а также, возможно, какие-то дополнительные свойства.
Для этой цели создаём интерфейсную библиотеку.
Привязываем заголовки к нашей интерфейсной библиотеке.
Установим стандарт языка. Разумеется, самый последний. При этом не просто включаем стандарт, но и распространяем его на тех, кто будет использовать нашу библиотеку. Это достигается за счёт того, что установленное свойство имеет категорию INTERFACE (см. команду target_compile_features).
Заводим псевдоним для нашей библиотеки. Причём для красоты он будет в специальном «пространстве имён». Это будет полезно, когда в нашей библиотеке появятся разные модули, и мы заходим подключать их независимо друг от друга. Как в Бусте, например.
Установка
Установка наших заголовков в систему. Тут всё просто. Говорим, что папка со всеми заголовками должна попасть в директорию include относительно места установки.
Тесты
Документация
Документация также не будет генерироваться в случае подпроекта.
Онлайн-песочница
Аналогично, онлайн-песочницы у подпроекта тоже не будет.
Скрипт для тестов (test/CMakeLists.txt)
Тестирование
Первым делом находим пакет с нужным тестовым фреймворком (замените на свой любимый).
А файлы, в которых описаны сами тесты, добавляю позже. Но так делать не обязательно.
Наконец, создаём фиктивную цель, «сборка» которой эквивалентна запуску тестов, и добавляем эту цель в сборку по умолчанию (за это отвечает атрибут ALL ). Это значит, что сборка по умолчанию инициирует запуск тестов, то есть мы никогда не забудем их запустить.
Покрытие
Скрипт для документации (doc/CMakeLists.txt)
Дальше проверяем, установлена ли пользователем переменная с языком. Если да, то не трогаем, если нет, то берём русский. Затем конфигурируем файлы системы Doxygen. Все нужные переменные, в том числе и язык попадают туда в процессе конфигурации (см. команду configure_file ).
Скрипт для онлайн-песочницы (online/CMakeLists.txt)
Проект снаружи
Теперь рассмотрим, как этим всем пользоваться.
Сборка
Сборка данного проекта, как и любого другого проекта на системе сборки CMake, состоит из двух этапов:
Генерация
Сборка проекта
Опции
MYLIB_COVERAGE
MYLIB_TESTING
MYLIB_DOXYGEN_LANGUAGE
Переключает язык документации, которую генерирует цель doc на заданный. Список доступных языков см. на сайте системы Doxygen.
По умолчанию включён русский.
Сборочные цели
По умолчанию
mylib-unit-tests
Компилирует модульные тесты. Включено по умолчанию.
check
Запускает собранные (собирает, если ещё не) модульные тесты. Включено по умолчанию.
coverage
Анализирует запущенные (запускает, если ещё не) модульные тесты на предмет покрытия кода тестами при помощи программы gcovr.
Выхлоп покрытия будет выглядеть примерно так:
Запускает генерацию документации к коду при помощи системы Doxygen.
wandbox
Ответ от сервиса выглядит примерно так:
Для этого используется сервис Wandbox. Не знаю, насколько у них резиновые сервера, но думаю, что злоупотреблять данной возможностью не стоит.
Примеры
Сборка проекта в отладочном режиме с замером покрытия
Установка проекта без предварительной сборки и тестирования
Сборка в выпускном режиме заданным компилятором
Генерирование документации на английском
Инструменты
На самом деле версия CMake 3.13 требуется только для запуска некоторых консольных команд, описанных в данной справке. С точки зрения синтаксиса CMake-скриптов достаточно версии 3.8, если генерацию вызывать другими способами.
Тестирование можно отключать (см. опцию MYLIB_TESTING ).
Для автоматической генерации онлайн-песочницы.
Статический анализ
С помощью CMake и пары хороших инструментов можно обеспечить статический анализ с минимальными телодвижениями.
Cppcheck
В CMake встроена поддержка инструмента для статического анализа Cppcheck.
Для этого нужно воспользоваться опцией _CPPCHECK»> CMAKE_CXX_CPPCHECK :
После этого статический анализ будет автоматически запускаться каждый раз во время компиляции и перекомпиляции исходников. Ничего дополнительного делать не нужно.
Clang
При помощи чудесного инструмента scan-build тоже можно запускать статический анализ в два счёта:
Послесловие
CMake — очень мощная и гибкая система, позволяющая реализовывать функциональность на любой вкус и цвет. И, хотя, синтаксис порой оставляет желать лучшего, всё же не так страшен чёрт, как его малюют. Пользуйтесь системой сборки CMake на благо общества и с пользой для здоровья.