cmake 从放弃到入门(2)

#Set the location for library installation -- i.e., /usr/lib in this case
# not really necessary in this example. Use "sudo make install" to apply
install(TARGETS testStudent DESTINATION /usr/lib)

两个重要变化:
1. 我们不再使用add_executable() 而是使用add_library()
2. install 指定安装目录,执行sudo make install时动态库将被安装在/usr/lib目录
如前两个例子,我们依次执行,cmake make编译结果如下:

这里写图片描述

例4:静态库编译 (.a)

基于例3,我们编译一个静态库,代码位置
exploringBB/extras/cmake/studentlib_static/

这里写图片描述


将CMakeList.txt修改为如下所示:

cmake_minimum_required(VERSION 2.8.9)
project(directory_test)
set(CMAKE_BUILD_TYPE Release)

#Bring the headers, such as Student.h into the project
include_directories(include)

#However, the file(GLOB...) allows for wildcard additions:
file(GLOB SOURCES "src/*.cpp")

#Generate the static library from the sources
add_library(testStudent STATIC ${SOURCES})

#Set the location for library installation -- i.e., /usr/lib in this case
# not really necessary in this example. Use "sudo make install" to apply
install(TARGETS testStudent DESTINATION /usr/li

可以看出,只需将add_library中的shared改为static即可。
编译结果如下:

这里写图片描述

例5:使用静态库或动态库

下边我们来测试一下我们例3的结果,代码和CMakeList.txt如下:

#include"Student.h"

int main(int argc, char *argv[]){
  Student s("Joe");
  s.display();
  return 0;
}

cmake_minimum_required(VERSION 2.8.9)
project (TestLibrary)

#For the shared library:
set ( PROJECT_LINK_LIBS libtestStudent.so )
link_directories( ~/exploringBB/extras/cmake/studentlib_shared/build )

#For the static library:
#set ( PROJECT_LINK_LIBS libtestStudent.a )
#link_directories( ~/exploringBB/extras/cmake/studentlib_static/build )

include_directories(~/exploringBB/extras/cmake/studentlib_shared/include)

add_executable(libtest libtest.cpp)
target_link_libraries(libtest ${PROJECT_LINK_LIBS} )

结果如下(CMakeList.txt中的目录要根据自己的情况改一下):


成功了!!

Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/12510.html