Step1: 基本开始
文件结构:
----Tutorial
|----build
|----CMakeLists.txt
|----tutorial.cpp
CMakeLists.txt:
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)
tutorial.cpp: 一个计算平方根的例子
// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stdout,"Usage: %s number\n",argv[0]);
return 1;
}
double inputValue = atof(argv[1]);
double outputValue = sqrt(inputValue);
fprintf(stdout,"The square root of %g is %g\n",
inputValue, outputValue);
return 0;
}
build 目录下cmake .. (cmake 后面是CMakeLists.txt的相对路径,这里是在build上一级目录中,所以是"..")
make
运行build下生成的可执行文件:
./Tutorial 9 (计算9的平方根)版本控制:
文件结构:
----Tutorial
|----build
|----CMakeLists.txt
|----tutorial.cpp
|----Tutorial.h.in
文件结构:
----Tutorial
|----build
|----CMakeLists.txt
|----tutorial.cpp
|----Tutorial.h.in
CMakeLists.txt:cmake_minimum_required (VERSION 2.6)
project (cmaketest)
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
"${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
"${PROJECT_BINARY_DIR}/TutorialConfig.h"
)
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
include_directories("${PROJECT_BINARY_DIR}")
# add the executable
add_executable(Tutorial tutorial.cpp)
Tutorial.h.in
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
tutorial.cpp:
// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
int main (int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stdout,"%s Version %d.%d\n",
argv[0],
Tutorial_VERSION_MAJOR,
Tutorial_VERSION_MINOR);
fprintf(stdout,"Usage: %s number\n",argv[0]);
return 1;
}
double inputValue = atof(argv[1]);
double outputValue = sqrt(inputValue);
fprintf(stdout,"The square root of %g is %g\n",
inputValue, outputValue);
return 0;
}
build目录下cmake ..
make
执行:./Tutorial
输出版本信息
./Tutorial Version 2.0
Usage: ./Tutorial number
Step 2: 添加库