cmake入门系列总结二
版本说明
版本 | 作者 | 日期 | 备注 |
---|---|---|---|
0.1 | loon | 2019.3.12 | 初稿 |
目录
一、目的
现在我们将为我们的项目添加一个库。该库将由我们自己实现,用于打印一个hellWorld。然后,可执行程序可以使用此库而不是重新调用打印函数打印helloWorld。
二、添加库
在本教程中,我们将把库放入一个名为printHellWorld的子目录中。它将包含以下一行CMakeLists.txt文件:
add_library(printHellWorld printHelloWorld.cpp)
printHelloWorld.cpp如下:
#include <stdio.h>
void printHelloWorld()
{
printf("HelloWorld-test to add library!\n");
return;
}
源文件helloWorld.cpp有一个名为printHelloWorld的函数,它提供打印helloWorld的功能。要使用新库,我们在顶级CMakeLists.txt文件中添加add_subdirectory调用,以便构建库。我们还添加了另一个include目录,以便可以找到函数原型的printHellWorld/printHellWorld.h头文件。最后一个更改是将新库添加到可执行文件中。顶级CMakeLists.txt文件的最后几行现在看起来像:
cmake_minimum_required(VERSION 2.8)
project(helloWorld)
#指定头文件位置
include_directories(${PROJECT_SOURCE_DIR}/printHelloWorld)
#添加子目录
add_subdirectory(printHelloWorld)
#添加可执行文件
add_executable(helloWorld main.cpp)
#添加生成可执行文件链接的库
target_link_libraries(helloWorld printHelloWorld)
main.cpp如下:
#include "printHelloWorld.h"
int main()
{
printHelloWorld();
return 0;
}
目录结构如下:
zy@zy-virtual-machine:~/test/cmake_test/hello_world$ tree ./
./
├── CMakeLists.txt
├── main.cpp
└── printHelloWorld
├── CMakeLists.txt
├── printHelloWorld.cpp
└── printHelloWorld.h
1 directory, 5 files
执行过程:
zy@zy-virtual-machine:~/test/cmake_test/hello_world/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
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zy/test/cmake_test/hello_world/build
zy@zy-virtual-machine:~/test/cmake_test/hello_world/build$ make
Scanning dependencies of target printHelloWorld
[ 25%] Building CXX object printHelloWorld/CMakeFiles/printHelloWorld.dir/printHelloWorld.cpp.o
[ 50%] Linking CXX static library libprintHelloWorld.a
[ 50%] Built target printHelloWorld
Scanning dependencies of target helloWorld
[ 75%] Building CXX object CMakeFiles/helloWorld.dir/main.cpp.o
[100%] Linking CXX executable helloWorld
[100%] Built target helloWorld
zy@zy-virtual-machine:~/test/cmake_test/hello_world/build$ ls
CMakeCache.txt CMakeFiles cmake_install.cmake helloWorld Makefile printHelloWorld
zy@zy-virtual-machine:~/test/cmake_test/hello_world/build$ ./helloWorld
HelloWorld-test to add library!
三、让库可选
这部分暂时不要在非GUI系统上用,我在Ubuntu下使用时一直存在问题,暂时放弃。