git clone https://github.com/derekmolloy/exploringBB.git
#include
int main(int argc, char *argv[]){
std::cout << "Hello World!" << std::endl;
return 0;
}
CMakeLists.txt也只有三行而已(使用cmake管理项目的过程,也就是编写CMakeLists.txt的过程)
cmake_minimum_required(VERSION 2.8.9)
project (hello)
add_executable(hello helloworld.cpp)
第一行用于指定cmake最低版本
第二行指定项目名称(这个名称是任意的)
第三行指定编译一个可执行文件,hello是第一个参数,表示生成可执行文件的文件名(这个文件名也是任意的),第二个参数helloworld.cpp则用于指定源文件。
如果您电脑上已经安装了cmake,那么我们就已经完事具备了。
第一步,用cmake生成Makefile文件
cmake命令后边跟的就是CMakelist.txt所在的目录,这个目录不必是当前目录,你也可以新建一个build目录或者其他名字的目录来生成build文件,实际项目中也都是这么做的,这样代码会很干净也便于git管理:
第二步,make编译程序,编译成功
通过上一步我们发现,当前目录下已经多出了几个文件,特别是Makefile文件
第三步,测试程序
到此,第一个用cmake管理的程序,成功了!
实例的目录结构如下图:
cmake_minimum_required(VERSION 2.8.9)
project(directory_test)
#Bring the headers, such as Student.h into the project
include_directories(include)
#Can manually add the sources using the set command as follows:
#set(SOURCES src/mainapp.cpp src/Student.cpp)
#However, the file(GLOB...) allows for wildcard additions:
file(GLOB SOURCES "src/*.cpp")
add_executable(testStudent ${SOURCES})
和第一个例子比起来,CMakelist.txt有如下改变:
CMakelist.txt如下:
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 shared library from the sources
add_library(testStudent SHARED ${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/lib)
两个重要变化:
将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即可。
编译结果如下:
#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中的目录要根据自己的情况改一下):
成功了!!