Use cmake in Linux to build applications

Source: Internet
Author: User
Tags windows visual
Use cmake in Linux to build applications









This article introduces a cross-platform automated build system cmake in Linux
. Cmake is
Tools that are easier to use can free programmers from complicated compilation and connection processes. This article introduces how to use cmake through some examples.
Methods for handling multi-source file directories, finding and using other development kits, and generating debug and release programs.
Cmake Introduction

Cmake is a cross-platform automated construction system that uses the name cmakelists.txt
To describe the build process, you can generate standard build files, such as UNIX makefile or Windows visual c ++
Projects/workspaces. The file cmakelists.txt needs to be manually written. You can also write a script to generate it semi-automatically. Cmake
Provides more concise syntax than AutoConfig. The process for generating and compiling makefile using cmake on Linux is as follows:

1. Write cmakelists.txt.
2. Run "cmake path" or "ccmake path" to generate the makefile (path is the directory where cmakelists.txt is located ).
3. Use the make command for compilation.

First Project

Assume that there is only one source file main. cpp in our project.

Listing 1 source file main. cpp

 

#include<iostream>
int main()
{
std::cout<<"Hello word!"<<std::endl;
return 0;
}

To build this project, we need to write the file cmakelists.txt and put it in the same directory as main. cpp:

Listing 2 cmakelists.txt

 

1 PROJECT(main)
2 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
3 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
4 ADD_EXECUTABLE(main ${DIR_SRCS})

Cmakelists.txt
The syntax is relatively simple. It consists of commands, comments, and spaces. commands are case-insensitive, and the content after the symbol "#" is considered as comments. The command consists of the command name, Parentheses, and parameters.
Use spaces for interval. For example, for the cmakelists.txt file in Listing 2: the first line is a command named project and the parameter is main
The project name is main. The command line 2 limits the cmake version. The third line uses the command aux_source_directory
Assign the source file name in the current directory to the variable dir_srcs. The description of the command aux_source_directory in the cmake manual is as follows:

aux_source_directory(<dir> <variable>)

This command assigns the <dir> all source file names to the <variable> parameter. The fourth line uses the command add_executable to indicate that the source file in the dir_srcs variable needs to be compiled into an executable file named main.

After compiling the file cmakelists.txt, you must use the cmake or ccmake command to generate the makefile. The difference between ccmake and cmake is that ccmake provides a graphical operation interface. The cmake command is executed as follows:

cmake [options] <path-to-source>

Here we enter the directory where main. cpp is located and run "cmake." To Get The makefile and compile it using make, as shown in.

Figure 1. camke running result

 

How to process multiple source file directories

 

Cmake is easy to process distribution of source code in different directories. Assume that the source code distribution is as follows:

Figure 2. source code distribution

 

The files under the src directory must be compiled into a Linked Library.

Step 1: cmakelists.txt in the main directory of the project

Create the file cmakelists.txt in step 2. The file content is as follows:

Cmakelists.txt in step 2 in listing 3

1 PROJECT(main)
2 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
3 ADD_SUBDIRECTORY( src )
4 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
5 ADD_EXECUTABLE(main ${DIR_SRCS}  )
6 TARGET_LINK_LIBRARIES( main Test )

Compared with listing 2, this file adds the following content: the third line, use the command add_subdirectory to indicate that this project contains a sub-directory SRC
. Line 6: run the target_link_libraries command to specify that the executable file main needs to connect to a linked library named test.

Step 2: cmakelists.txt In the subdirectory

Create cmakelists.txt In the SRC subdirectory. The file content is as follows:

Listing 4. cmakelists.txt In the src directory

1 AUX_SOURCE_DIRECTORY(. DIR_TEST1_SRCS)
2 ADD_LIBRARY ( Test ${DIR_TEST1_SRCS})

Use the add_library command in this file to compile the source files in the src directory into a shared library.

Step 3: Execute cmake

Now we have completed the compilation of all the cmakelists.txt files in the project. Go to the directory Step 2 and execute the commands "cmake." and "make" in sequence. The result is as follows:

Figure 3. cmake execution result when processing multiple source file directories

During cmake execution, the cmakelists.txt in step 2 is parsed first. When the program executes the add_subdirectory (SRC) command, the src directory is used to parse the cmakelists.txt.

Find and use other library methods in the project


We will use some function libraries when developing software. These function libraries may be installed in different systems in different locations, during compilation, you must first find the header file of these software packages and the directory where the link library is located
The compilation option is generated. For example, if you want to use a bokeli database project, you need the header file db_cxx.h and the Link Library libdb_cxx.so.
Now, the project contains the source code file main. cpp, which is placed in the root directory of the project.

Step 1: Library description file

Create the directory cmake/modules/in the root directory of the project, and create the findlibdb_cxx.cmake file under cmake/modules/. The content is as follows:

Listing 5. File findlibdb_cxx.cmake

 01
Message (status "using bundled findlibdb. cmake ...")
02

03
Find_path (
04
Libdb_cxx_include_dir
05 db_cxx.h
06
/Usr/include/
07
/Usr/local/include/
08
)
09

10 find_library (
11
Libdb_cxx_libraries names db_cxx
12
Paths/usr/lib // usr/local/lib/
13
)

The findlibdb_cxx.cmake file must comply with the naming rules: findlibname. cmake, where name
Is the name of the function library. The findlibdb_cxx.cmake syntax is the same as that of cmakelists.txt. Here, three commands are used: message,
Find_path and find_library.

The command message will output the parameter content to the terminal.
The find_path command specifies the path to search for the header file. The prototype is as follows:
Find_path (<var>
Name1 [path1 path2...]) Find the file name1 in the directory indicated by path * and save the path to the variable
Var. Line 3-8 of Listing 5 indicates finding the file db_cxx.h in/usr/include/and/usr/local/include /.
And save the path of db_cxx.h in libdb_cxx_include_dir.
The find_library command is the same
Similar to find_path, it is used to find the Linked Library and save the result in the variable. The line 10-13 in listing 5 indicates the directory/usr/lib/and
In/usr/local/lib/, find the link library named db_cxx and save the result in libdb_cxx_libraries.
Step 2: cmakelist.txt in the project root directory

Create cmakelist.txt in the project root directory:

Listing 6. You can find the cmakelist.txt

 01
Project (main)
02
Cmake_minimum_required (version 2.6)
03
Set (cmake_source_dir .)
04
Set (cmake_module_path$ {

Cmake_root}

/Modules$ {

Cmake_source_dir}

/Cmake/modules)
05 aux_source_directory (. dir_srcs)
06
Add_executable (main$ {

Dir_srcs}

)
07

08
Find_package (libdb_cxx required)
09
Mark_as_advanced (
10 libdb_cxx_include_dir
11
Libdb_cxx_libraries
12
)
13
If (libdb_cxx_include_dir and libdb_cxx_libraries)
14
Message (status "found libdb libraries ")
15
Include_directories ($ {

Libdb_cxx_include_dir}

)
16
Message ($ {

Libdb_cxx_libraries}

)
17
Target_link_libraries (main$ {

Libdb_cxx_libraries}


18
)
19
Endif (libdb_cxx_include_dir and libdb_cxx_libraries)

In this file, lines 4th indicate to the directory./cmake/modules to find findlibdb_cxx.cmake, 8-19
The row indicates the process of searching the Link Library and header file. Run the find_package command to find the find_package. After the command is executed, cmake returns the variable
Find and execute the findlibdb_cxx.cmake file in the directory indicated by cmake_module_path. Line 13-19 is a condition judgment statement, indicating that if
Libdb_cxx_include_dir and libdb_cxx_libraries have been assigned values.
Libdb_cxx_include_dir
.

Step 3: Execute cmake

After findlibdb_cxx.cmake and cmakelist.txt are compiled, execute "cmake." and "make" in the root directory of the project. The result is shown in:

Figure 4. cmake execution results when other libraries are used


Use cmake to Generate debug and release programs

 

In Visual Studio, we can generate programs for debug and release, and use cmake
We can also achieve the above results. The executable file generated by the debug version project requires debugging information and does not need to be optimized, while the release
The version does not require debugging information but needs to be optimized. These features are determined by the compile-time parameters in gcc/g ++. If the optimization degree is adjusted to the highest level, you need to set the parameter-O3. The lowest value is-O0.
Optimization is not performed. The parameter for adding debugging information is-g-ggdb. If this parameter is not added, debugging information will not be included in the generated binary file.

The cmake variable cmake_build_type can be set to debug release.
Relwithdebinfo and minsizerel. When the value of this variable is debug, cmake uses the variable
Generate makefile using the string in cmake_cxx_flags_debug and cmake_c_flags_debug as the compilation Option
When the value of this variable is release, the project uses the variables cmake_cxx_flags_release and
The cmake_c_flags_release option generates the makefile.

Assume that there is only one file main. cpp in the project. Below is a cmakelist.txt program that can generate the debug and release versions:

Listing 7

 

1 PROJECT(main)
2 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
3 SET(CMAKE_SOURCE_DIR .)
4
5 SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
6 SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
7
8 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
9 ADD_EXECUTABLE(main ${DIR_SRCS})

The cmake_cxx_flags_debug and cmake_cxx_flags_release variables are set in rows 5th and 6,
These two variables are the compilation options for debug and release respectively. After editing cmakelist.txt, run the ccmake command to generate
Makefile. Enter "ccmake." In the root directory of the project to enter a graphical interface, as shown in:

Figure 5. ccmake Interface

 

Follow the prompts on the page and press "c" to perform Configure. The page displays the cmake_build_type configuration variable. As shown in:

Figure 6. ccmake interface after configure is executed

 

Next, we will first generate the makefile for Debug: Set the variable cmake_build_type to debug, and press "C"
Perform configure, generate makefile by "g", and exit. Run the find * | xargs grep "O0" command"
The result is as follows:

Listing 8 find * | xargs grep "O0" execution result

CMakeFiles/main.dir/flags.make:CXX_FLAGS = -O0 -Wall -g -ggdb 
CMakeFiles/main.dir/link.txt:/usr/bin/c++ -O0 -Wall -g -ggdb
CMakeFiles/main.dir/main.cpp.o -o main -rdynamic
CMakeLists.txt:SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")

The result shows that the generated makefile uses the variable cmake_cxx_flags_debug as the compile-time parameter.

Next we will generate the release makefile: Execute the command "ccmake." Again ."
Set the variable cmake_build_type to release, generate the makefile, and exit. Run find * | xargs
The result of grep "O0" is as follows:

Listing 9 find * | xargs grep "O0" execution result

Cmakelists.txt: Set (cmake_cxx_flags_debug "$ ENV {cxxflags}-O0-wall-g-ggdb ")

The result of executing the find * | xargs grep "O3" command is as follows:

Listing 10. Find * | xargs grep "O3" execution result

 

CMakeCache.txt:CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG
CMakeCache.txt:CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG
CMakeFiles/main.dir/flags.make:CXX_FLAGS = -O3 -Wall
CMakeFiles/main.dir/link.txt:/usr/bin/c++ -O3 -Wall
CMakeFiles/main.dir/main.cpp.o -o main -rdynamic
CMakeLists.txt:SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")

The two results indicate that the generated makefile uses the variable cmake_cxx_flags_release as the compile-time parameter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.