参考:https://www.hahack.com/codes/cmake/#
源文件一共有三个:main.cpp、MathFunctions.h、MathFunctions.cpp
文件内容分别如下:
main.cpp
#include
#include
#include "MathFunctions.h"
int main(int argc, char *argv[])
{
if (argc < ){
printf("Usage: %s base exponent \n", argv[]);
return ;
}
double base = atof(argv[]);
int exponent = atoi(argv[]);
double result = power(base, exponent);
printf("%g ^ %d is %g\n", base, exponent, result);
return ;
}
MathFunctions.h
#ifndef POWER_H
#define POWER_H
extern double power(double base, int exponent);
#endif
MathFunctions.cpp
/**
* power - Calculate the power of number.
* @param base: Base value.
* @param exponent: Exponent value.
*
* @return base raised to the power exponent.
*/
double power(double base, int exponent)
{
int result = base;
int i;
if (exponent == ) {
return ;
}
for(i = ; i < exponent; ++i){
result = result \* base;
}
return result;
}
CMakeLists.txt内容如下:
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
project (Demo2)
aux_source_directory(. DIR_SRCS)
add_executable(Demo ${DIR_SRCS})
这里需要学习的是使用变量获取目录下的所有源文件:
aux_source_directory(. DIR_SRCS)
# 指定生成目标
add_executable(Demo ${DIR_SRCS})
编译及执行结果如下:
wmz@ubuntu:~/Desktop/testcmake1$ cmake .
-- The C compiler identification is GNU 5.4.
-- The CXX compiler identification is GNU 5.4.
-- 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
[ %] Building CXX object CMakeFiles/Demo.dir/MatnFunctions.cpp.o
[ %] Building CXX object CMakeFiles/Demo.dir/main.cpp.o
[%] Linking CXX executable Demo
[%] 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
^ is
手机扫一扫
移动阅读更方便
你可能感兴趣的文章