zl程序教程

您现在的位置是:首页 >  其它

当前栏目

cmake一个简单的工程

一个 简单 工程 CMake
2023-09-27 14:20:16 时间

创建一个工程文件夹hello3,在里面创建一个字文件夹src,把main.cpp、hello.cpp、hello.hpp复制进去。

因为每个文件家里面都要有一个 CMakeists.txt 文件,于是hello3/src文件夹的内容如下:

ADD_EXECUTABLE(hello main.cpp hello.cpp)

工程文件夹hello3里面的内容

PROJECT(HELLO)
ADD_SUBDIRECTORY(src bin)

然后在工程文件夹hello3里面创建子文件夹build,进入该文件夹,运行:

$ cmake ..
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.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
CMake Warning (dev) in CMakeLists.txt:
  No cmake_minimum_required command is present.  A line of code such as

    cmake_minimum_required(VERSION 3.10)

  should be added at the top of the file.  The version specified may be lower
  if you wish to support older CMake versions for this project.  For more
  information run "cmake --help-policy CMP0000".
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Configuring done
-- Generating done
-- Build files have been written to: /media/yeping/Works/demos/d0003-hello/build

再make一下

$ make
Scanning dependencies of target hello
[ 33%] Building CXX object bin/CMakeFiles/hello.dir/main.o
[ 66%] Building CXX object bin/CMakeFiles/hello.dir/hello.o
[100%] Linking CXX executable hello
[100%] Built target hello

然后,在build文件夹内看到一个bin文件夹,里面有我们的目标文件hello。

可见,ADD_SUBDIRECTORY(src bin)中目标文件夹的位置是相对 build 文件夹的,如果改成下面的样子

ADD_SUBDIRECTORY(src ../bin)

目标代码的bin就和src位于文件夹树的同一个级别了。

可以通过 SET 指令重新定义 EXECUTABLE_OUTPUT_PATH 和 LIBRARY_OUTPUT_PATH 变量来指定最终的目标二进制的位置(指最终生成的 hello 或者最终的共享库,不包含编译生成的中间文件)

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)

_BINARY_DIR 和 PROJECT_BINARY_DIR 变量,他们指的编译发生的当前目录,如果是内部编译,就相当于PROJECT_SOURCE_DIR 也就是工程代码所在目录,如果是外部编译,指的是外部编译所在目录,也就是本例中的 build 目录。所以,上面两个指令分别定义了:可执行二进制的输出路径为 build/bin 和库的输出路径为 build/lib.
于是,CMakeLists.txt 文件可以更专业地写成下面形式

文件夹 hello3:

PROJECT(HELLO)
ADD_SUBDIRECTORY(src)

文件夹 hello3/src

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/../bin)
ADD_EXECUTABLE(hello main.cpp hello.cpp)

在 build 文件夹运行一下,OK!