Introduction to the use of Linux under CMake

Source: Internet
Author: User
Tags mul windows visual

CMake is a cross-platform compiled auto-configuration tool that uses a file called CMakeLists.txt to describe the build process, which can produce standard build files. It can use simple statements to describe the installation of all platforms (the compilation process). It can output a variety of Makefile or project files that can test the C + + features supported by the compiler, similar to the Automake under UNIX. CMake does not directly construct the final software, but rather produces standard constructs such as UNIX's makefile or Windows Visual C + + projects/workspaces, which are then used in a general constructive fashion.

CMake can compile the source code, make the library, generate the adapter (wrapper), and can construct the execution file in any order. CMake supports In-place construction (binary files and source code in the same directory tree) and out-of-place constructs (binary files in other directories), so it is easy to construct multiple binaries from the same source directory tree. CMake also supports the construction of static and dynamic libraries. CMake is a more advanced compilation configuration tool than make.

The CMake configuration file is named CMakeLists.txt. A configuration file is a CMake script written in a special programming language dedicated to building software. The file CMakeLists.txt needs to be written manually, or it can be generated semi-automatically by scripting. By writing CMakeLists.txt, you can control the generated makefile to control the compilation process.

CMake Main Features: (1), open source code, the use of the class BSD license release, (2), cross-platform, and can generate native compilation configuration file, on the Linux/unix platform, generate makefile; on the Apple platform, you can generate Xcode; on the Windows platform, can generate MSVC project files, (3), be able to manage large projects, (4), simplify the compilation build process and compile process, cmake tool chain is very simple: Cmake+make, (5), High Efficiency, (6), extensible, can write a specific function for CMake module, Expand the CMake function.

To see if the CMake and version numbers are installed on the Ubuntu14.0464, you can verify by executing the following statement:

$ cmake--version

If not installed, the following statements can be executed to install:

$ apt-get Install CMake

The syntax of CMakeLists.txt is simple, consisting of commands, comments, and spaces, where the commands are case-insensitive, the arguments and variables are case-sensitive, but all uppercase directives are recommended. The content after the symbol "#" is considered a comment. A command consists of a command name, parentheses, and parameters that are spaced between parameters using a space or semicolon. Variables are referenced using ${xxx}.

Common Command Description:

1. Aux_source_directory (<dir><variable>): This command assigns all source files (excluding header files) in parameter <dir> to parameters <variable>;

2. Find_path (<VAR> name1[path1 path2 ...]): This command finds the file name1 in the directory indicated by the parameter path* and saves the found path in variable VAR (where "[...]" is used. Contains an item that represents an ignorable item, using the "... | ... "To select only one of the items represented in a split item);

3. Find_library (${var} NAMES name1[name2 ...] PATHS path1 [path2 ...] Path_suffixes suffix1 [uffix2 ...]: Search for an external link library file and save the full path of the result to the Var variable. The name of the link library file to be searched may be name1,name2, etc., the search path is path1, path2, etc., also can specify the suffix word of the path is suffix1,suffix2, etc.;

4. Find_package (name): searches the specified module directory for a CMake script module file named Find<name>.cmake (for example, Findosg.cmake), and executes the contents of the Intent to search for the specified external dependent library header file and library file location;

5. Find_program: Search for an external executable program;

6. Project (name): Specify the project name;

7. Include (file): Contains the contents of another CMake script file in the current file for loading the CMakeLists.txt file and for loading the predefined cmake modules;

8. Include_directories: Specifies the search path of the header file to add multiple specific header file search paths to the project, which can be called multiple times to set multiple paths, equivalent to specifying the-i parameter of GCC;

9. Link_directories: Add non-standard shared library search path, set the external dynamic link library or static link library of the search path, equivalent to the GCC-l parameter;

Link_libraries: Add a link library;

Add_subdirectory: Used to add a subdirectory of the source file to the current project, and to specify the location where the intermediate binary and destination binaries are stored;

Add_executable: Compile executable program, specify compile, as if you can add. o file;

Add_definitions (-dmacro1-dmacro2 ...): Add compilation parameters, add-D precompiled macro definition, can add more than one at a time;

Add_dependencies: Defines the other target that the target relies on to ensure that the other target has been built before the target is translated;

Add_library: You can set the link library to be generated as shared or static, you can also set the module (plug-in, can be dynamically called, but not as a dependency of other projects);

Add_custom_target (name COMMANDCMD1 [COMMAND cmd2.]): Add a compiled directory named name, and specify one or more custom commands cmd1,cmd2, and so on; note add_custom_ command is different from this one: the former is the setting of custom compilation rules for an existing sub-project, while the latter is a new custom target project;

Target_link_libraries: You can use to add a shared library that needs to be linked for target, specify a dependent library for the project, add a link library, add a dynamic library, or a static library, equivalent to specifying the-l parameter;

Message: Print messages, output one or more lines of debug information in the Console or dialog box;

Set: Define a user-defined variable;

Set_target_properties: Used to set the name of the output, for the dynamic library, can also be used to specify the dynamic library version and API version;

Cmake_minimum_required: Set the dependent CMake version;

Configure_file (infile outfile): Copy the file infile to the outfile location while performing the automatic configuration and replacement of the variables;

Install: Installs the target project to the specified folder, this command is used to define the installation rules, the content of the installation can include target binary, dynamic library, static library and files, directories, scripts and so on;

Option (${var} "text" value): Provides an option to the user, with the hint message text, the initial value as value, and the final result passed to the VAR variable;

Enable_testing: Used to control whether the makefile builds test targets, involving all project catalogs;

Exec_program: Used to run a program in the specified directory;

Execute_process: Executes one or more sub-processes, running one or more commands in the order specified;

Document: File Operation command;

built-in variables, environment variables:

1. Cmake_c_compiler: Specify C compiler;

2. Cmake_cxx_compiler: Specify C + + compiler;

3. Cmake_c_flags: Specify compile options when compiling C files, such as-G, or you can add compilation options via Add_definitions;

4. Cmake_cxx_flags: Set C + + compilation options;

5. Cmake_build_type:build type (debug,release,...), Cmake_build_type=debug;

6. Cmake_command: The full path of the CMAKE executable file itself;

7. The Cmake_debug_postfix:debug version generates the suffix of the target, which can usually be set to the "D" character;

8. Cmake_generator: Compiler name, such as "Unixmakefiles", "Visual Studio 7", etc.;

9. Cmake_install_prefix: Engineering installation directory, all generate and invoke required executable program, library file, header file will be installed to the path, unix/linux under the default is/usr/local, Windows default is C:\Program Files;

Cmake_module_path: Sets the additional path to the Search Cmakemodules module (. CMAKE), which defines the path where the CMAKE module is located;

Cmake_current_source_dir: Refers to the path of the current processing CMakeLists.txt;

Cmake_current_binary_dir: If it is In-source compiled, it is consistent with cmake_current_source_dir; if it is out-of-source, it refers to the target compiler directory;

Cmake_current_list_file: Outputs the full path of the CMakeLists.txt that calls this variable;

Cmake_current_list_line: Outputs the row where this variable is located;

Cmake_include_current_dir: Automatically add Cmake_current_binary_dir and Cmake_current_source_dir to the current processing CMakeLists.txt;

Cmake_include_directories_project_efore: The header file directory provided by the project is always in front of the system header file directory and can provide some help when you define a header file that is in conflict with the system;

Executable_output_path: Specify the storage path of the executable file, the final result of the storage directory;

Library_output_path: Specify the library file storage path, the final result of the storage directory;

Build_shared_libs: Specifies whether to compile to a static or dynamic library;

Project_binary_dir (Cmake_binary_dir): If it is an internal build (in-sourcebuild), it refers to the top-level catalog of the project, and if it is an external build (Out-of-source build), Refers to the directory where the project compiles;

PROJECT_NAME: project name, which is the name set with the project command;

Project_source_dir (Cmake_source_dir): The directory where the project source code files are located, refers to the project top level directory;

CYGWIN: Identifies whether the current system is CYGWIN;

MSVC: Identifies whether the current system uses microsoftvisual C;

UNIX: Identifies whether the current system is a UNIX family (including Linux, Cygwin, and Apple);

WIN32: Identifies whether the current system is windows and Win64;

use of built-in variables:

1. Specify in CMakeLists.txt, use set;

2. Use in CMake order, such as Cmake-dbuild_shared_libs=off;

CMake How to invoke environment variables: Use the $env{name} directive to invoke the system's environment variables. As message (STATUS "Home dir: $ENV {home}")

Set environment variables by: Set (env{variable name} value)

Variable, expressed as ${my_vairable}, whose storage type is a string type, but can be automatically converted to a Boolean, integer, or floating-point type according to the requirements of the specific command. Variables can appear in strings, or they can be "introspective." Variables are user-defined and system-built, user-defined variables are set using SET commands, and system variables are automatically assigned by the system, such as ${project_source_dir}.

Conditional statements in CMake: IF (expression) ... ELSE (expression) ... ENDIF (expression) or if (expression1) ... ELSEIF (expression2) ... ELSE () ... ENDIF (), expression is the judging condition, similar to C + +, cmake conditions also exist "and/or/not" and "equals/greater/less than" operators, respectively, with And/or/not and Equal/less/greater to represent. If control statements, variables are referenced directly using the variable name, without the need for ${}.

Looping statements in CMake: FOREACH (vararg1 arg2 ...) ... Endforeach (Var), set a cyclic local variable var, each time it is assigned as ARG1, arg2 a value in a variable (or array of variables), and executes the command segment in the loop.

The macro function in CMake can be understood as a C-language function that alters the flow of code to perform jumps and simplifies the development of scripts: Macro (funcname [arg1 [arg2 ...]) ... Endmacro (funcname), like the writing requirements of functions, cmake macro functions must have a function name funcname, and 0 or more input parameters arg1,arg2 and so on. The need to call the macro function, as long as the direct use of funcname (arg1 arg2) Form is possible.

CMake first run, it will produce a file called CMakeCache.txt, which can be viewed as a configuration file, and its contents are like the set of parameters passed to the Configure command.

The following examples illustrate the detailed use of CMake:

The total directory structure is:

The contents of each file are:

1.1 make_api.h

#!/bin/bashset-eproj_root= $PWDBUILD _root= $PROJ _rootecho "build ROOT: $BUILD _root" If ["$" = = "--no-test"]; The-P option for Thenno_test=1elseno_test=0fi#mkdir allows you to create multiple levels of directories at once instead of just creating separate directories at a time mkdir-p $BUILD _ROOT/BUILDCD $BUILD _root/ Buildcmake-dcmake_cxx_flags=-g-dcmake_build_type=release-dcmake_install_prefix:path= $BUILD _root/install $PROJ _ Rootmake-j5make Install >/dev/nullmkdir-p $BUILD _ROOT/API/BUILDCD $BUILD _root/api/buildcmake-dcmake_build_type= Release-dno_testbench= $NO _test-dsdk_install_path= $BUILD _root/install-dcmake_install_prefix:path= $PROJ _root/api _install $PROJ _root/apimake-j5make Install >/dev/null
1.2 CMakeLists.txt

#/cmake/cmakelists.txtproject (MATH_SDK) cmake_minimum_required (VERSION 2.8) MESSAGE ("Start Build") add_subdirectory (add_sub) Add_subdirectory (Mul_div)
1.3 Add_sub

1.3.1 CMakeLists.txt

#/cmake/add_subadd_subdirectory (ADD) add_subdirectory (sub) #目录的安装 #install (DIRECTORY./add/src/#DESTINATION include /add/#FILES_MATCHING  PATTERN "*.h" #) #INSTALL (DIRECTORY./sub/src/#DESTINATION include/sub/#FILES_MATCHING PATTERN "*.h" #)

1.3.2 Add

1.3.2.1 SRC

1.3.2.1.1 AddOper.cpp

#include "addOper.h" int caladd (int a, int b) {return (A + b);}
1.3.2.1.2 AddOper.h

#ifndef _add_oper_h_#define _add_oper_h_int caladd (int a, int b); #endif
1.3.2.2 CMakeLists.txt

#/cmake/add_sub/addaux_source_directory (./src add_src_list) add_library (Add_oper static${add_src_list}) INSTALL ( DIRECTORY./src/destination include/add_sub/addfiles_matching PATTERN "*.h") INSTALL (TARGETS add_operdestination Lib)
1.3.3 Sub

1.3.3.1 SRC

1.3.3.1.1 SubOper.cpp

#include "subOper.h" int calsub (int a, int b) {return (a);}
1.3.3.1.2 SubOper.h

#ifndef _sub_oper_h_#define _sub_oper_h_int calsub (int a, int b); #endif
1.3.3.2 CMakeLists.txt

#/cmake/add_sub_subaux_source_directory (./src sub_src_list) add_library (Sub_oper static${sub_src_list}) INSTALL ( DIRECTORY./src/destination include/add_sub/subfiles_matching PATTERN "*.h") INSTALL (TARGETS sub_operdestination Lib)
1.4 API

1.4.1 Include

1.4.1.1 MathOper.h

#ifndef _math_oper_h_#define _math_oper_h_int caladdsub (int a, int b); int calmuldiv (int a, int b); #endif

1.4.2 SDK

1.4.2.1 CMakeLists.txt

#/cmake/api/sdkaux_source_directory (. sdk_src_list) include_directories (${sdk_install_path}/include/add_sub) include_directories (${SDK_INSTALL_PATH}/ Include/mul_div) add_library (mathsdk SHARED ${sdk_src_list}) SET (dep_libs${sdk_install_path}/lib/libadd_oper.a${ SDK_INSTALL_PATH}/LIB/LIBSUB_OPER.A${SDK_INSTALL_PATH}/LIB/LIBMUL_OPER.A${SDK_INSTALL_PATH}/LIB/LIBDIV_OPER.A) Target_link_libraries (Mathsdk ${dep_libs}) INSTALL (TARGETS mathsdkdestination Lib)
1.4.2.2 MathOper.cpp

#include "mathOper.h" #include "add/addoper.h" #include "sub/suboper.h" #include "mul/muloper.h" #include "div/ DivOper.h "int caladdsub (int a, int b) {int c = 0, d = 0;c = Caladd (A, b);d = Calsub (A, B); return (c + D);} int calmuldiv (int a, int b) {int c = 0, d = 0;c = Calmul (A, b);d = Caldiv (A, B); return (c-d);}
1.4.3 Test

1.4.3.1 CMakeLists.txt

#/cmake/api/testaux_source_directory (. test_src_list) include_directories (${cmake_install_prefix}/include) add_executable (Test ${TEST_SRC_LIST}) SET (DEP_ LIB ${cmake_install_prefix}/lib/libmathsdk.so) target_link_libraries (Test ${dep_lib}) INSTALL (TARGETS Testdestination bin)
1.4.3.2 Demo.cpp

#include "MathOper.h" #include <iostream>int main () {int a = ten, b = 2;int C = Caladdsub (A, b); int d = Calmuldiv (A, B) ;std::cout<< "c =" <<c<<std::endl;//c = 20std::cout<< "D =" <<d<<std::endl;//d = 15return 0;}
1.4.4 CMakeLists.txt

#/cmake/apiproject (MATH_API) cmake_minimum_required (VERSION 2.8) MESSAGE ("==============start build api============ = = ") SET (cmake_shared_linker_flags" ${cmake_shared_linker_flags}-Z defs-pthread ") include_directories (${SDK_ install_path}/include/add_sub) include_directories (${sdk_install_path}/include/mul_div) LINK_DIRECTORIES (${SDK_ Install_path}/lib) include_directories (INCLUDE) add_subdirectory (SDK) if (not no_testbench) add_subdirectory (test) endif () INSTALL (DIRECTORY./include/destination include)
1.5 Mul_div

1.5.1 Div

1.5.1.1 SRC

1.5.1.1.1 DivOper.cpp

#include "divOper.h" int caldiv (int a, int b) {return (A/b);}
1.5.1.1.2 DivOper.h

#ifndef _div_oper_h_#define _div_oper_h_int caldiv (int a, int b); #endif
1.5.1.2 CMakeLists.txt

#/cmake/mul_div/divaux_source_directory (./src div_src_list) add_library (Div_oper static${div_src_list}) INSTALL ( DIRECTORY./src/destination include/mul_div/divfiles_matching PATTERN "*.h") INSTALL (TARGETS div_operdestination Lib)
1.5.2 Mul

1.5.2.1 SRC

1.5.2.1.1 MulOper.cpp

#include "mulOper.h" int calmul (int a, int b) {return (A * b);}
1.5.2.1.2 MulOper.h

#ifndef _mul_oper_h_#define _mul_oper_h_int Calmul (int a, int b); #endif
1.5.2.2 CMakeLists.txt

#/cmake/mul_div/mulaux_source_directory (./src mul_src_list) add_library (Mul_oper static${mul_src_list}) INSTALL ( DIRECTORY./src/destination include/mul_div/mulfiles_matching PATTERN "*.h") INSTALL (TARGETS mul_operdestination Lib)
1.5.3 CMakeLists.txt

#/cmake/mul_divadd_subdirectory (mul) add_subdirectory (DIV)

Operating instructions:

1. Execution in CMake directory: $ sh make_api.sh

2. Implementation: $ export Ld_library_path=/cmake/api_install/lib

3. Execution: $./api_install/bin/test


Reference documents:

1. http://www.ibm.com/developerworks/cn/linux/l-cn-cmake/

2. http://blog.chinaunix.net/uid-28458801-id-3501768.html

3. http://www.hahack.com/codes/cmake/

4. Http://www.cnblogs.com/rickyk/p/3877238.html?utm_source=tuicool

5. http://www.docin.com/p-728984407.html

6. http://www.doc88.com/p-7485437070242.html

7. http://www.cmake.org/cmake/help/v3.3/index.html

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to the use of Linux under CMake

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.