Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

25.2. CMake

http://www.cmake.org/

25.2.1. helloworld

安裝CMake

$ sudo yum install gcc gcc-c++
$ sudo yum install make

$ sudo yum install cmake28
$ sudo ln -s /usr/bin/cmake28 /usr/bin/cmake
$ cmake --version
cmake version 2.8.9
		

創建 CMakeLists.txt 檔案

$ cat CMakeLists.txt
PROJECT(example)
ADD_EXECUTABLE(example main.c)
		

創建 main.c 檔案

		
$ cat main.c
#include <stdio.h>
int main() {
   printf("helloworld!\n");
   return 0;
}
		
		

編譯程序

$ cmake .
-- Configuring done
-- Generating done
-- Build files have been written to: /home/neo/example

$ make
Scanning dependencies of target example
[100%] Building C object CMakeFiles/example.dir/main.c.o
Linking C executable example
[100%] Built target example

$ ./example
helloworld!
		

25.2.2. cmake_minimum_required

cmake_minimum_required(VERSION 2.8.7)
		

25.2.3. SET

SET(CMAKE_INSTALL_PREFIX /usr/local)
		

改變 CMAKE_INSTALL_PREFIX 變數

cmake -DCMAKE_INSTALL_PREFIX=/usr ..
		

25.2.4. ADD_SUBDIRECTORY

ADD_SUBDIRECTORY(src bin)
		

25.2.5. INCLUDE_DIRECTORIES

INCLUDE_DIRECTORIES(/usr/include/xen)
		

相當於 gcc -I/usr/include/xen

25.2.6. 編譯檔案

25.2.6.1. ADD_EXECUTABLE 編譯可執行

SET(SRC_LIST main.cc
        src/file1.c
        src/file2.c
        )

ADD_EXECUTABLE(hello ${SRC_LIST})
			

25.2.6.2. ADD_LIBRARY 編譯庫檔案

編譯 *.a 檔案

$ cat  CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
PROJECT(zeromq)
ADD_LIBRARY(zeromq zeromq.c)
INCLUDE_DIRECTORIES(/usr/include/mysql)
TARGET_LINK_LIBRARIES(zeromq zmq)
			

編譯共享庫 *.so 檔案

$ cat  CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
PROJECT(zeromq)
ADD_LIBRARY(zeromq SHARED zeromq.c)
INCLUDE_DIRECTORIES(/usr/include/mysql)
TARGET_LINK_LIBRARIES(zeromq zmq)
			

25.2.7. EXECUTABLE_OUTPUT_PATH / LIBRARY_OUTPUT_PATH

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
		

25.2.8. TARGET_LINK_LIBRARIES

TARGET_LINK_LIBRARIES(hello log4cpp)
TARGET_LINK_LIBRARIES(hello zmq)
		

相當於 gcc -lzmq

25.2.9. INSTALL

INSTALL(PROGRAMS hello DESTINATION bin)

INSTALL(FILES COPYRIGHT README DESTINATION share/doc/hello)

INSTALL(DIRECTORY doc/ DESTINATION share/doc/hello)