ubuntu@ubuntu:$ vim tutorial.cxx
ubuntu@ubuntu:$ cat tutorial.cxx
// A simple program that computes the square root of a number#include<cmath>#include<cstdlib>#include<iostream>#include<string>intmain(int argc,char* argv[]){if(argc <2){
std::cout <<"Usage: "<< argv[0]<<" number"<< std::endl;return1;}// convert input to doubleconstdouble inputValue =atof(argv[1]);// calculate square rootconstdouble outputValue =sqrt(inputValue);
std::cout <<"The square root of "<< inputValue <<" is "<< outputValue
<< std::endl;return0;}
CMake file
ubuntu@ubuntu:$ vim CMakeLists.txt
ubuntu@ubuntu:$ cat CMakeLists.txt
#TODO : Set the minimum required version of CMake to be 3.10cmake_minimum_required(VERSION 3.10)#TODO : Create a project named Tutorialproject(Tutorial)#TODO : Add an executable called Tutorial to the project#Hint: Be sure to specify the source file as tutorial.cxxadd_executable(Tutorial tutorial.cxx)
ubuntu@ubuntu:$
构建cmake工程
ubuntu@ubuntu:$ ls -tlr
total 12
-rw-r--r-- 1 ubuntu ubuntu 775 Oct 1222:26 tutorial.cxx
-rw-r--r-- 1 ubuntu ubuntu 679 Oct 1716:50 CMakeLists.txt
ubuntu@ubuntu:$ mkdir exercise1_build
ubuntu@ubuntu:$ ls -tlr
total 16
-rw-r--r-- 1 ubuntu ubuntu 775 Oct 1222:26 tutorial.cxx
-rw-r--r-- 1 ubuntu ubuntu 679 Oct 1716:50 CMakeLists.txt
drwxrwxr-x 2 ubuntu ubuntu 4096 Oct 1717:04 exercise1_build
ubuntu@ubuntu:$ cd exercise1_build/
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/exercise1_build
ubuntu@ubuntu:$ ls -tlr
total 32
-rw-rw-r-- 1 ubuntu ubuntu 14355 Oct 1717:05 CMakeCache.txt
-rw-rw-r-- 1 ubuntu ubuntu 5549 Oct 1717:07 Makefile
-rw-rw-r-- 1 ubuntu ubuntu 1730 Oct 1717:07 cmake_install.cmake
drwxrwxr-x 6 ubuntu ubuntu 4096 Oct 1717:07 CMakeFiles
ubuntu@ubuntu:$ cmake --build .[50%] Building CXX object CMakeFiles/Tutorial.dir/tutorial.cxx.o
[100%] Linking CXX executable Tutorial
[100%] Built target Tutorial
ubuntu@ubuntu:$
运行可执行文件
```bash
ubuntu@ubuntu:$ ls -tlr
total 48-rw-rw-r--1 ubuntu ubuntu 14355 Oct 1717:05 CMakeCache.txt
-rw-rw-r--1 ubuntu ubuntu 5549 Oct 1717:07 Makefile
-rw-rw-r--1 ubuntu ubuntu 1730 Oct 1717:07 cmake_install.cmake
-rwxrwxr-x 1 ubuntu ubuntu 13152 Oct 1717:08 Tutorial
drwxrwxr-x 6 ubuntu ubuntu 4096 Oct 1717:08 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
ubun@ubuntu:$ pwd