CMake入门(1. 简单程序)

参考:/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下面,其他的类似,可以先不深入了解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值