ubuntu@ubuntu:$ vim tutorial.cxx
ubuntu@ubuntu:$ cat tutorial.cxx
// A simple program that computes the square root of a number#include<cmath>#include<iostream>#include<string>intmain(int argc,char* argv[]){if(argc <2){
std::cout <<"Usage: "<< argv[0]<<" number"<< std::endl;return1;}// convert input to double// std::stod是C++ 11标准函数constdouble inputValue = std::stod(argv[1]);// calculate square rootconstdouble outputValue =sqrt(inputValue);
std::cout <<"The square root of "<< inputValue <<" is "<< outputValue
<< std::endl;return0;}
ubuntu@ubuntu:$
CMake file
ubuntu@ubuntu:$ vim CMakeLists.txt
ubuntu@ubuntu:$ cat CMakeLists.txt
# TODO : Set the minimum required version of CMake to be 3.10
cmake_minimum_required(VERSION 3.10)
# TODO : Create a project named Tutorial
project(Tutorial)
# TODO : Set the variable CMAKE_CXX_STANDARD to 11
# and the variable CMAKE_CXX_REQUIRED_STANDARD to True
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# TODO : Add an executable called Tutorial to the project
# Hint: Be sure to specify the source file as tutorial.cxx
add_executable(Tutorial tutorial.cxx)
ubuntu@ubuntu:$
构建cmake工程
ubuntu@ubuntu:$ ls -tlr
-rw-r--r-- 1 ubuntu ubuntu 825 Oct 1717:23 tutorial.cxx
-rw-r--r-- 1 ubuntu ubuntu 743 Oct 1717:23 CMakeLists.txt
ubuntu@ubuntu:$ mkdir exercise2_build/
ubuntu@ubuntu:$ ls -tlr
-rw-r--r-- 1 ubuntu ubuntu 825 Oct 1717:23 tutorial.cxx
-rw-r--r-- 1 ubuntu ubuntu 743 Oct 1717:23 CMakeLists.txt
drwxrwxr-x 2 ubuntu ubuntu 4096 Oct 1717:31 exercise2_build
ubuntu@ubuntu:$ cd exercise2_build/
ubuntu@ubuntu:$ ls -tlr
total 0
ubuntu@ubuntu:$ cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: /home/ubuntu/study/cmake-learning/cmake-3.25.0-rc1-tutorial-source/Step1/exercise2_build
ubuntu@ubuntu:$ cmake --build .
ubuntu@ubuntu:$ ls -tlr
total 48
-rw-rw-r-- 1 ubuntu ubuntu 14355 Oct 1717:32 CMakeCache.txt
-rw-rw-r-- 1 ubuntu ubuntu 5549 Oct 1717:32 Makefile
-rw-rw-r-- 1 ubuntu ubuntu 1730 Oct 1717:32 cmake_install.cmake
-rwxrwxr-x 1 ubuntu ubuntu 14824 Oct 1717:32 Tutorial
drwxrwxr-x 6 ubuntu ubuntu 4096 Oct 1717:32 CMakeFiles
运行可执行文件
ubuntu@ubuntu:$ ./Tutorial 4294967296
The square root of 4.29497e+09 is 65536
ubuntu@ubuntu:$ ./Tutorial 10
The square root of 10 is 3.16228
ubuntu@ubuntu:$ ./Tutorial
Usage: ./Tutorial number
ubuntu@ubuntu:$