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)