install CMake
我用CMake並不關注它的跨平台特性,因為我只專註於64位 Linux C++ server領域。
sudo apt-get install cmake
# cmake --versioncmake version 2.8.7
HelloWorld工程
mkdir -p examples/helloworld
cd examples/helloworld
建立main.cpp 檔案,代碼如下:
#include <stdio.h>int main(){ printf("Hello World from Main!\n"); return 0;}
建立CMakeLists.txt檔案,配置如下:
PROJECT (HELLOWorld)SET(SRC_LIST main.cpp)MESSAGE(STATUS "This is BINARY dir " ${HELLO_BINARY_DIR})MESSAGE(STATUS "This is SOURCE dir "${HELLO_SOURCE_DIR})ADD_EXECUTABLE(hello ${SRC_LIST})
在同目錄下,運行cmake .
chenshu@chenshu-ubuntu:~/Ubuntu One/c++/cmake/examples/helloworld$ cmake .
— The C compiler identification is GNU
— The CXX compiler identification is GNU
— Check for working C compiler: /usr/bin/gcc
— Check for working C compiler: /usr/bin/gcc — works
— Detecting C compiler ABI info
— Detecting C compiler ABI info - 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
— This is BINARY dir /home/chenshu/Ubuntu One/c++/cmake/examples/helloworld
— This is SOURCE dir /home/chenshu/Ubuntu One/c++/cmake/examples/helloworld
— Configuring done
— Generating done
— Build files have been written to: /home/chenshu/Ubuntu One/c++/cmake/examples/helloworld
Makefile以及其他一些檔案被cmake產生了。執行make命令,hello二進位檔案被編譯出來。運行./hello,可以看到結果。
Hello World from Main!
make VERBOSE=1 可以看到詳細的編譯過程。
make clean 就可以清理工程
外部構建
HelloWorld採用內部構建,cmake產生的代碼和自己的原始碼檔案在同一個目錄,非常不好。因此需要採用cmake的外部構建方式。
建立helloworld2目錄
這次建立一個src目錄存放原始碼,doc目錄存放項目文檔,
CMakeLists.txt需要出現在項目根目錄和src目錄中。
項目根目錄下的內容如下:
project (HelloWorld2)
add_subdirectory(src bin)
src目錄下內容如下:
add_executable(hello2 main.cpp)
建立一個build目錄
cd build
cmake ..
make
build/bin下會找到hello2可執行檔。
支援gdb調試
在src/CMakeLists.txt檔案中添加一行: set(CMAKE_BUILD_TYPE Debug)