📜  cmake (1)

📅  最后修改于: 2023-12-03 15:30:01.618000             🧑  作者: Mango

CMake

CMake is an open-source cross-platform build system generator. It is used to build, test, and package software written in C++, C, and other languages.

Installation

CMake can be downloaded from the official website. There are also several package managers, such as Homebrew on macOS or apt on Ubuntu, that can be used to install CMake.

Usage
Creating a CMake project

To create a new CMake project, create a new directory for your project and create a file called CMakeLists.txt in that directory. This file will contain the configuration information for your project.

Here is an example CMakeLists.txt file:

cmake_minimum_required(VERSION 3.10)

# Set the project name
project(MyProject)

# Add an executable
add_executable(MyProject main.cpp)

This file sets the minimum required version of CMake, sets the name of the project to "MyProject", and adds an executable called "MyProject" that is built from main.cpp.

Building the project

To build the project, navigate to the directory that contains CMakeLists.txt and run the following commands:

mkdir build
cd build
cmake ..
make

These commands will create a new directory called build, configure the project using CMake, and build the project using the make command.

Adding libraries

To include external libraries in your CMake project, you can use the add_library() command to create a library target:

# Add an external library
add_library(MyLibrary STATIC IMPORTED)
set_target_properties(MyLibrary PROPERTIES IMPORTED_LOCATION /path/to/libMyLibrary.a)

This example adds an external library called "MyLibrary" and sets its location to /path/to/libMyLibrary.a.

You can then link this library to your executable using the target_link_libraries() command:

# Link the external library
target_link_libraries(MyProject MyLibrary)
Cross-compiling

CMake can be used to cross-compile projects for different platforms. To cross-compile, you must specify the target platform using the CMAKE_SYSTEM_NAME variable:

# Set the target platform
set(CMAKE_SYSTEM_NAME Linux)

# Set the target architecture
set(CMAKE_SYSTEM_PROCESSOR arm)

# Set the C/C++ compilers for the target platform
set(CMAKE_C_COMPILER /path/to/arm-gcc)
set(CMAKE_CXX_COMPILER /path/to/arm-g++)

This example sets the target platform to Linux, the target architecture to ARM, and sets the C/C++ compilers for the target platform.

Conclusion

CMake is a powerful build system generator that can be used to build, test, and package software written in C++, C, and other languages. By using CMake, you can easily create cross-platform projects, include external libraries, and configure your project with ease.