cmake使用实践(二)
本文演示将代码可执行文件,cmake生成文件分开,涉及到多层目录编写CMakeLists.txt
之后所有的构建都选择out-of-source外部构建,一般选择工程目录下的build目录
1、准备工作
目录层次结构
————test2
|——CMakeLists.txt
|——src
|——hello.cpp
|——CMakeLists.txt
工程内容包括,一个子目录src,一个CMakeLists.txt,一个项目工程需要对任何一个子目录建立一个CMakeLists.txt
2、代码内容
根目录的CMakeLists.txt
<pre name="code" class="html">cmake_minimum_required(VERSION 2.8)
project(HELLO)
add_subdirectory(src)
src目录的 CMakeLists.txt
#制定可执行文件的输出目录,输出到bin下面
set(EXECUTABLE_OUTPUT_PATH ${HELLO_SOURCE_DIR}/bin)
#message(STATUS "source dir " ${PROJECT_SOURCE_DIR})
#指定可执行文件名和相关源文件
add_executable(hello hello.cpp)
#制定库文件输出路径
set(LIBRARY_OUTPUT_PATH ${HELLO_SOURCE_DIR}/lib)
#生成动态库
#前面已经使用target文件名hello不能再使用
add_library(hello_so SHARED hello.cpp)
#设置输出名为hello=>libhello.so
set_target_properties(hello_so PROPERTIES OUTPUT_NAME "hello")
#生成静态库
add_library(hello_a STATIC hello.cpp)
#设置库输出名字
set_target_properties(hello_a PROPERTIES OUTPUT_NAME "hello")
hello.cpp
#include<iostream>
using namespace std;
int main()
{
cout << "Hello Cmake!!!" << endl;
return 0;
}
然后在工程目录下建立一个build目录,切换到build目录
~/cmake/test2/build$ cmake ..
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- source dir /home/quan/cmake/test2
-- Configuring done
-- Generating done
-- Build files have been written to: /home/quan/cmake/test2/build
make
:~/cmake/test2/build$ make
Scanning dependencies of target hello
[ 16%] Building CXX object src/CMakeFiles/hello.dir/hello.cpp.o
[ 33%] Linking CXX executable ../../bin/hello
[ 33%] Built target hello
Scanning dependencies of target hello_so
[ 50%] Building CXX object src/CMakeFiles/hello_so.dir/hello.cpp.o
[ 66%] Linking CXX shared library ../../lib/libhello.so
[ 66%] Built target hello_so
Scanning dependencies of target hello_a
[ 83%] Building CXX object src/CMakeFiles/hello_a.dir/hello.cpp.o
[100%] Linking CXX static library ../../lib/libhello.a
[100%] Built target hello_a
切换到工程根目录,查看文件列表,发现已经生成了lib和bin目录,cmake生成的文件则存放在build中
~/cmake/test2$ ls
bin build CMakeLists.txt lib src
语法
add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])
指令用于向当前工程添加存放源文件的子目录,