欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CMake tutorial(1. start)

程序员文章站 2024-03-23 11:48:34
...

参考:/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)

# 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)                                                       
  • 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

执行

$ ./bin/hello
Hello World