参考:/https://tuannguyen68.gitbooks.io/learning-cmake-a-beginner-s-guide/content/chap1/chap1.html
文件目录如下
test
├── CMakeLists.txt
└── test.cpp
- CMakeLists.txt
# Specify the minimun version for CMake
cmake_minimum_required(VERSION 2.8)
# Project's name
project(hello)
add_executable(hello test.cpp)
- test.cpp
#include<iostream>
using namespace std;
int main() {
cout << "hello world" << endl;
return 0;
}
运行一下命令
$ cmake -H. -Bbuild
$ cmake --build build -- -j3
之后就会生成可执行文件,-j3是用cpu的3个线程执行。
以上的命令其实相当于
$ mkdir build
$ cd build
$ 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/rhf/test/build
$ make
Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/test.cpp.o
[100%] Linking CXX executable ../bin/hello
[100%] Built target hello
执行
$ cd build
$ ./hello
Hello World
可以把CMakeLists.txt改成,重新编译一下
# Specify the minimun version for CMake
cmake_minimum_required(VERSION 2.8)
# Project's name
project(hello)
# Set the outpyt foldfer where your program will be created
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
# The following folder will be included
include_directories("${PROJECT_SOURCE_DIR}")
add_executable(hello ${PROJECT_SOURCE_DIR}/test.cpp)
CMAKE_BINARY_DIR
是我们生成执行文件的目录,相当于windows下.exe生成的目录。
CMAKE_SOURCE_DIR
就是我们CMakeLists.txt所在的目录。
我们用set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
。指定生成的可执行目录在test/bin
下面,其他的类似,可以先不深入了解。