CMake 使用入门

http://derekmolloy.ie/hello-world-introductions-to-cmake/

 

CMake is a cross-platform Makefile generator

 

1 CMakeLists.txt ——helloworld

cmake_minimum_required(VERSION 2.8.9)

project (hello)

add_executable(hello helloworld.cpp)

The first line is CMake Version for this project, which is major version 2, minor version 8, and patch version 9 in this example.
The second line is the project() command that sets the project name
The third line is the add_executable() command, which requests that an executable is to be built using the helloworld.cpp source file. The first argument to the 
  add_executable() function is the name of the executable to be built, and the second argument is the source file from which to build the executable.


编译方法:
1 cd $YOUR_DIR/exploringBB/extras/cmake/helloworld
2 cmake .
3 make

 

2 使用单独的build目录放置编译结果

1 mkdir build
2 cd build
3 cmake ..
4 make

 

3 多目录结构的CMakeLists.txt

 1 cmake_minimum_required(VERSION 2.8.9)
 2 project(directory_test)
 3 
 4 #Bring the headers, such as Student.h into the project
 5 include_directories(include)
 6 
 7 #Can manually add the sources using the set command as follows:
 8 #set(SOURCES src/mainapp.cpp src/Student.cpp)
 9 
10 #However, the file(GLOB...) allows for wildcard additions:
11 file(GLOB SOURCES "src/*.cpp")
12 
13 add_executable(testStudent ${SOURCES})

 

4 静态库结构的示例

 1 cmake_minimum_required(VERSION 2.8.9)
 2 project(directory_test)
 3 set(CMAKE_BUILD_TYPE Release)
 4 
 5 #Bring the headers, such as Student.h into the project
 6 include_directories(include)
 7 
 8 #However, the file(GLOB...) allows for wildcard additions:
 9 file(GLOB SOURCES "src/*.cpp")
10 
11 #Generate the shared library from the sources
12 add_library(testStudent SHARED ${SOURCES})
13 
14 #Set the location for library installation -- i.e., /usr/lib in this case
15 # not really necessary in this example. Use "sudo make install" to apply
16 install(TARGETS testStudent DESTINATION /usr/lib)

 

结果如下:

1 -rw-rw-r--. 1 hadoop hadoop 12355 Jul 28 02:36 CMakeCache.txt
2 drwxrwxr-x. 5 hadoop hadoop  4096 Jul 28 02:36 CMakeFiles
3 -rw-rw-r--. 1 hadoop hadoop  2594 Jul 28 02:36 cmake_install.cmake
4 -rw-rw-r--. 1 hadoop hadoop  3192 Jul 28 02:36 libtestStudent.a
5 -rw-rw-r--. 1 hadoop hadoop  6820 Jul 28 02:36 Makefile

 

安装库:

1 sudo make install
 

5 引用外部链接库的方法

 1 cmake_minimum_required(VERSION 2.8.9)
 2 project (TestLibrary)
 3 
 4 #For the shared library:
 5 set ( PROJECT_LINK_LIBS libtestStudent.so )
 6 link_directories( ~/exploringBB/extras/cmake/studentlib_shared/build )
 7 
 8 #For the static library:
 9 #set ( PROJECT_LINK_LIBS libtestStudent.a )
10 #link_directories( ~/exploringBB/extras/cmake/studentlib_static/build )
11 
12 include_directories(~/exploringBB/extras/cmake/studentlib_shared/include)
13 
14 add_executable(libtest libtest.cpp)
15 target_link_libraries(libtest ${PROJECT_LINK_LIBS} )

posted @ 2016-07-28 17:56  thoughtflare  阅读(332)  评论(0编辑  收藏  举报