cmake教程step 2

step 2  向项目中添加库

  在这一步中,我们实现自己到sqrt函数,并用CMakeLists.txt添加到我们到项目中. 

首先,我们在项目目录中增加一个子目录 : MathFunctions,用来放置我们的sqrt的实现.  我们在MathFunctions目录下创建两个文件: mysqrt.c 和 mysqrt.h

内容分别为

mysqrt.h:

1 float mysqrt(float) ;

mysqrt.c:

1 #include "mysqrt.h"
2 float mysqrt(float x)     {
3     return x*x;
4 }

然后向在MathFunctions目录下创建 CMakeLists.txt 并 添加如下内容:

1 add_library(MathFunctions mysqrt.c)

最后的顶层目录下到CMakeLists.txt文件如下:

 1 cmake_minimum_required (VERSION 2.6)
 2 project (Tutorial)
 3 # The version number.
 4 set (Tutorial_VERSION_MAJOR 1)
 5 set (Tutorial_VERSION_MINOR 0)
 6  
 7 # configure a header file to pass some of the CMake settings
 8 # to the source code
 9 configure_file (
10   "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
11   "${PROJECT_BINARY_DIR}/TutorialConfig.h"
12   )
13  
14 # add the binary tree to the search path for include files
15 # so that we will find TutorialConfig.h
16 include_directories("${PROJECT_BINARY_DIR}")
17 
1819 
20 include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
21 add_subdirectory (MathFunctions) 
22  
23 # add the executable
24 add_executable(Tutorial hello.c)
25 target_link_libraries (Tutorial MathFunctions)

现在我们考虑将MathFunctions库变成可配置的,可在项目顶层目录中的CMakeLists.txt中添加下面到代码可以实现:

1 # should we use our own math functions?
2 option (USE_MYMATH
3     "Use tutorial provided math implemention"  ON)
 1 # add the MathFunctions library?
 2 #
 3 if (USE_MYMATH)
 4   include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
 5   add_subdirectory (MathFunctions)
 6   set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
 7 endif (USE_MYMATH)
 8  
 9 # add the executable
10 add_executable (Tutorial tutorial.c)
11 target_link_libraries (Tutorial  ${EXTRA_LIBS})

 

 

 

 

posted @ 2013-12-05 00:00  mayer21548  阅读(425)  评论(0编辑  收藏  举报