Cmake how to add library
Cmake how to add library
Введение в 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 можно очищать\удалять без риска поломать исходники. Если 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 в одном коммерческом проекте. Буду рад, если статья поможет хотя бы одному человеку — на русском языке подобной документации довольно мало.
How to add prebuilt static library in project using CMake?
Clion: how add or (use) prebuilt static library in my Project?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I had great difficulty making this work as I was completely new to CLion and CMake.
In my scenario I was taking a class that required us to use the course library in every project.
First, find the library’s location:
LIB_TO_INCLUDE will contain the location of the library assuming it is found. Note that hardcoding the path could be problematic if you’d like your solution to be portable to other systems. You can add additional search paths separated by a space if the library could exist in multiple locations. A typical example is to include common install locations such as /usr/bin /usr/local/bin etc.
Next, ensure that header files (if applicable) are included in the header search paths:
Again, include multiple search paths if the headers could be loaded in multiple locations. If there is more than one header file, you’ll need to include all of them.
Now, include the directories using the include_directories command:
The above will instruct the build system to search all directories contained in LIB_INCLUDES or whatever you decide to call it.
That’s all. You’ll notice that under «External Libraries» > «Header Search Paths» in the Project organizer window the directories containing your header files appears.
Step 2: Adding a LibraryВ¶
Now we will add a library to our project. This library will contain our own implementation for computing the square root of a number. The executable can then use this library instead of the standard square root function provided by the compiler.
Add the following one line CMakeLists.txt file to the MathFunctions directory:
To make use of the new library we will add an add_subdirectory() call in the top-level CMakeLists.txt file so that the library will get built. We add the new library to the executable, and add MathFunctions as an include directory so that the MathFunctions.h header file can be found. The last few lines of the top-level CMakeLists.txt file should now look like:
Now let us make the MathFunctions library optional. While for the tutorial there really isn’t any need to do so, for larger projects this is a common occurrence. The first step is to add an option to the top-level CMakeLists.txt file.
This option will be displayed in the cmake-gui and ccmake with a default value of ON that can be changed by the user. This setting will be stored in the cache so that the user does not need to set the value each time they run CMake on a build directory.
The next change is to make building and linking the MathFunctions library conditional. To do this, we will create an if statement which checks the value of the option. Inside the if block, put the add_subdirectory() command from above with some additional list commands to store information needed to link to the library and add the subdirectory as an include directory in the Tutorial target. The end of the top-level CMakeLists.txt file will now look like the following:
Note the use of the variable EXTRA_LIBS to collect up any optional libraries to later be linked into the executable. The variable EXTRA_INCLUDES is used similarly for optional header files. This is a classic approach when dealing with many optional components, we will cover the modern approach in the next step.
Then, in the same file, make USE_MYMATH control which square root function is used:
Since the source code now requires USE_MYMATH we can add it to TutorialConfig.h.in with the following line:
Run the cmake executable or the cmake-gui to configure the project and then build it with your chosen build tool. Then run the built Tutorial executable.
Rebuild and run the tutorial again.
How do I add a library path in cmake?
I have 2 folders «inc» and «lib» in my project which have headers and static libs respectively. How do I tell cmake to use those 2 directories for include and linking respectively?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The simplest way of doing this would be to add
might fail working with link_directories, then add each static library like following:
You had better use find_library command instead of link_directories. Concretely speaking there are two ways:
designate the path within the command
set the variable CMAKE_LIBRARY_PATH
set(CMAKE_LIBRARY_PATH path1 path2)
find_library(NAMES gtest)
the reason is as flowings:
Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).
If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.
add_libraryВ¶
Add a library to the project using the specified source files.
Normal LibrariesВ¶
New in version 3.8: A STATIC library may be marked with the FRAMEWORK target property to create a static Framework.
If a library does not export any symbols, it must not be declared as a SHARED library. For example, a Windows resource DLL or a managed C++/CLI DLL that exports no unmanaged symbols would need to be a MODULE library. This is because CMake expects a SHARED library to always have an associated import library on Windows.
If EXCLUDE_FROM_ALL is given the corresponding property will be set on the created target. See documentation of the EXCLUDE_FROM_ALL target property for details.
See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
See also HEADER_FILE_ONLY on what to do if some sources are pre-processed, and you want to have the original sources reachable from within IDE.
Object LibrariesВ¶
Interface LibrariesВ¶
and then it is used as an argument to target_link_libraries() like any other target.
An interface library created with the above signature has no source files itself and is not included as a target in the generated buildsystem.
New in version 3.15: An interface library can have PUBLIC_HEADER and PRIVATE_HEADER properties. The headers specified by those properties can be installed using the install(TARGETS) command.
New in version 3.19: An interface library target may be created with source files:
Source files may be listed directly in the add_library call or added later by calls to target_sources() with the PRIVATE or PUBLIC keywords.
If an interface library has source files (i.e. the SOURCES target property is set), or header sets (i.e. the HEADER_SETS target property is set), it will appear in the generated buildsystem as a build target much like a target defined by the add_custom_target() command. It does not compile any sources, but does contain build rules for custom commands created by the add_custom_command() command.
Imported LibrariesВ¶
The must be one of:
References a library file located outside the project. The IMPORTED_LOCATION target property (or its per-configuration variant «> » title=»IMPORTED_LOCATION_ «> IMPORTED_LOCATION_ ) specifies the location of the main library file on disk:
Additional usage requirements may be specified in INTERFACE_* properties.
References a set of object files located outside the project. The IMPORTED_OBJECTS target property (or its per-configuration variant «> » title=»IMPORTED_OBJECTS_ «> IMPORTED_OBJECTS_ ) specifies the locations of object files on disk. Additional usage requirements may be specified in INTERFACE_* properties.
Does not reference any library or object files on disk, but may specify usage requirements in INTERFACE_* properties.
See documentation of the IMPORTED_* and INTERFACE_* properties for more information.
Alias LibrariesВ¶
New in version 3.11: An ALIAS can target a GLOBAL Imported Target
New in version 3.18: An ALIAS can target a non- GLOBAL Imported Target. Such alias is scoped to the directory in which it is created and below. The ALIAS_GLOBAL target property can be used to check if the alias is global or not.
Источники информации:
- http://stackoverflow.com/questions/29368026/how-to-add-prebuilt-static-library-in-project-using-cmake
- http://cmake.org/cmake/help/latest/guide/tutorial/Adding%20a%20Library.html
- http://stackoverflow.com/questions/28597351/how-do-i-add-a-library-path-in-cmake
- http://cmake.org/cmake/help/latest/command/add_library.html