cmake使用01:只包含一个源文件的项目

项目仅有一个源文件

项目文件夹./step1,如下
./build/为构建目录

   ./step1/
      |--build/
      |--Tutorial.cxx
      |--CMakeList.txt

Tutorial.cxx,开平方

#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
  if (argc < 2) {
    std::cout << "Usage: " << argv[0] << " number" << std::endl;
    return 1;
  }

  // convert input to double
  const double inputValue = atof(argv[1]);

  // calculate square root
  const double outputValue = sqrt(inputValue);
  std::cout << "The square root of " << inputValue << " is " << outputValue
            << std::endl;
  return 0;
}

Cmakefile内容如下:

cmake_minimum_required(VERSION 3.10)

# 项目名
project(Tutorial)

# 生成可执行文件。相当于g++ tutorial.cxx -o Tutorial
add_executable(Tutorial tutorial.cxx) 
  1. cmake执行构建
# 1.切换到构建目录。
cd ./build

# 2. 实际执行效果cmake ../CMakeLists.txt生成Makefile:

cmake ..

# 3. 实际执行效果make  Makefile 进行实际的项目构建(编译-连接-测试-安装):

#等价 cmake --build .
make 

构建结果

   step1/
      |--build/
            |---Makefile
            |---Tutorial
      |--Tutorial.cxx
      |--CMakeList.txt
  1. 执行可执行文件Tutorial
    生成的可执行文件Tutorial默认是放置在Makefile所在目录下,也就是./build/。
cd ./build
./Tutorial 100 #输出10

重点:

  1. CMakeList.txt的源文件的相对路径为CMAKE_SOURCE_DIR(CMakeList.txt所在目录)
  2. cmake .. 输出为Cmakefile,存放至该条命令执行所在的工作目录,也就是./step1/build/Cmakefile,
  3. cmake --build . 生成可执行文件,存放至Cmakefile所在目录,即./step1/build/Tutorial
posted @ 2024-06-27 22:13  旅行者2号  阅读(1)  评论(0编辑  收藏  举报