HELLO CMAKE - 第一个 CMake 工程

942 阅读2分钟

Hello,CMake

那么如何写一个 最初的 CMake 管理的程序呢?

一般现代 Linux 操作系统都是自带 CMake, gcc, make 的,因为这也正是很多 Linux 开源软件所必须的。 我们现在来编写一个简易的 CMake 生成可执行程序的工程,本例子在各种常用的 linux 发行版中都可以使用,不管是 ubuntu, centos, deepin, manjaro 都可以。

我使用的是 manjaro 操作系统,安装了 CMake 插件的 VS Code 编辑器。

新建工程结构

第一步,我们新建一个空白文件夹hello_cmake,然后用 VS Code 打开该文件夹。

创建一个简单的工程,一共三个源文件,分别是main.cpphello.h,hello.cpp。 文件的内容如下:

/// hello.h
# pragma once

void PrintHello();

/// hello.cpp
# include "hello.h"
#include <iostream>

using namespace std;

void PrintHello( )
{
    cout << "Hello CMake!" << endl;
}

/// main.cpp
#include "hello.h"

int main()
{
    PrintHello();
    return 0;
}

非常简洁的三个源文件,我们让 main 文件引用 hello.h 中声明的、定义在 hello.cpp中的函数

编辑 CMakeLists.txt

接着,在目录中新建一个 CMake 工程文件,文件名为 CMakeLists.txt,文件名不要写错,否则可能会找不到文件。

CMakeLists.txt中填写如下内容:

# 工程名,可以随便起
project(HELLO_CMAKE)    

# 设置工程编译好的可执行文件放在输出文件夹的那个路径里
# 此处设置的是输出路径下 xxx/bin 文件夹中
# ${} 是CMake访问变量内容的一种方式,会被替换为该变量名的实际内容
# PROJECT_SOURCE_DIR 和 PROJECT_BINARY_DIR 是CMAKE 自带变量,指向工程的源文件路径和实际编译的路径
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)

# 设置导出可执行程序,这里起名为 hello,
# 可执行程序的名称与工程名无关,一个工程可以编译出多个可执行程序
# ADD_EXECUTABLE(program_name file1,file2,...)
add_executable(hello main.cpp hello.cpp)

编译工程

通常情况下,我们采用外部构建的方法编译我们的程序,这样可以使得源文件与目标文件及各类中间文件分离,使工程路径更干净些。

mkdir build
cd build
cmake ..
make

如果你执行了上述的代码,可能会见到如下的输出

[chaoqun@manjaro hello_cmake]$ cd hello_cmake/
[chaoqun@manjaro hello_cmake]$ ls
CMakeLists.txt  hello.cpp  hello.h  main.cpp
[chaoqun@manjaro hello_cmake]$ mkdir build
[chaoqun@manjaro hello_cmake]$ cd build/
[chaoqun@manjaro build]$ ls
[chaoqun@manjaro build]$ cmake ..
-- The C compiler identification is GNU 9.2.0
-- The CXX compiler identification is GNU 9.2.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/chaoqun/workspace/learning/hello_cmake/hello_cmake/build
[chaoqun@manjaro build]$ make
Scanning dependencies of target hello
[ 33%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[ 66%] Building CXX object CMakeFiles/hello.dir/hello.cpp.o
[100%] Linking CXX executable bin/hello
[100%] Built target hello
[chaoqun@manjaro build]$ ls
CMakeCache.txt  CMakeFiles  Makefile  bin  cmake_install.cmake
[chaoqun@manjaro build]$ ./bin/hello 
Hello CMake!

至此,我们便编译好了一个最简单的 CMake 工程。

Reference

  1. 代码样例
  2. CMake Partice
  3. Wikipedia