Reference: https://www.hahack.com/codes/cmake/#
There are three source files: main.cpp, MathFunctions.h, MathFunctions.cpp
File contents are as follows:
main.cpp
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include "MathFunctions.h" 4 5 int main(int argc, char *argv[]) 6 { 7 if (argc < 3){ 8 printf("Usage: %s base exponent \n", argv[0]); 9 return 1; 10 } 11 double base = atof(argv[1]); 12 int exponent = atoi(argv[2]); 13 double result = power(base, exponent); 14 printf("%g ^ %d is %g\n", base, exponent, result); 15 return 0; 16 }
MathFunctions.h
1 #ifndef POWER_H 2 #define POWER_H 3 4 extern double power(double base, int exponent); 5 6 #endif
MathFunctions.cpp
1 /** 2 * power - Calculate the power of number. 3 * @param base: Base value. 4 * @param exponent: Exponent value. 5 * 6 * @return base raised to the power exponent. 7 */ 8 double power(double base, int exponent) 9 { 10 int result = base; 11 int i; 12 13 if (exponent == 0) { 14 return 1; 15 } 16 17 for(i = 1; i < exponent; ++i){ 18 result = result * base; 19 } 20 21 return result; 22 }
CMakeLists.txt reads as follows:
# CMake minimum version requirements cmake_minimum_required (VERSION 2.8 ) # Project Information Project (Demo2) # find all files in the source directory # and name to save DIR_SRCS variable aux_source_directory (. DIR_SRCS) # generate specified target add_executable (Demo $ {DIR_SRCS} )
Here need to learn is to use a variable to obtain a directory of all the source files:
aux_source_directory (. DIR_SRCS)
# Specify generate a target
add_executable (Demo $ {DIR_SRCS})
Compilation and execution results are as follows:
wmz@ubuntu:~/Desktop/testcmake1$ cmake . -- The C compiler identification is GNU 5.4.0 -- The CXX compiler identification is GNU 5.4.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/wmz/Desktop/testcmake1 wmz@ubuntu:~/Desktop/testcmake1$ make Scanning dependencies of target Demo [ 33%] Building CXX object CMakeFiles/Demo.dir/MatnFunctions.cpp.o [ 66%] Building CXX object CMakeFiles/Demo.dir/main.cpp.o [100%] Linking CXX executable Demo [100%] Built target Demo wmz@ubuntu:~/Desktop/testcmake1$ ls CMakeCache.txt CMakeLists.txt Makefile CMakeFiles Demo MathFunctions.h cmake_install.cmake main.cpp MatnFunctions.cpp wmz@ubuntu:~/Desktop/testcmake1$ ./Demo 2 3 2 ^ 3 is 8