Cmake共享库

时间:2015-11-15 11:34:55

标签: makefile cmake

我正在学习CMake,但我很难理解如何将二进制文件链接到共享库,然后将这些文件安装在发行文件夹中。

这是我项目的结构:

├── CMakeLists.txt
├── build
├── main
│   ├── CMakeLists.txt
│   └── main.cpp
├── release
|_______bin 
│   ├── include
│   │   └── math.h
│   └── lib
│       └── libmathLib.dylib
└── shared_lib
    ├── CMakeLists.txt
    ├── include
    │   └── math.h
    └── src
        └── math.cpp

在根CMakeLists.txt中,我已经定义了项目设置和子目录。

Root CMakeLists.txt:

cmake_minimum_required(VERSION 3.1)

project (Math)
set(CMAKE_BUILD_TYPE Release)

set(MAKE_INCLUDE_CURRENT_DIR ON)

ADD_SUBDIRECTORY(shared_lib)
ADD_SUBDIRECTORY(main)

主要CMakeLists.txt:

add_executable(main main.cpp)
TARGET_LINK_LIBRARIES(main LINK_PUBLIC mathLib)

Math lib(共享库)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)

add_library(mathLib SHARED src/math.cpp)

install(TARGETS mathLib DESTINATION /Users/giuseppe/development/cmake/release/lib LIBRARY NAMELINK_ONLY)
install(FILES include/math.h DESTINATION /Users/giuseppe/development/cmake/release/include)

当我使用Make构建项目时,它不会将main.o链接到共享库。错误:

Scanning dependencies of target mathLib
[ 50%] Building CXX object shared_lib/CMakeFiles/mathLib.dir/src/math.cpp.o
Linking CXX shared library libmathLib.dylib
[ 50%] Built target mathLib
Scanning dependencies of target main
[100%] Building CXX object main/CMakeFiles/main.dir/main.cpp.o
/Users/giuseppe/development/cmake/main/main.cpp:8:12: error: use of undeclared identifier 'sum'
  count << sum(5,6) << endl;
           ^
1 error generated.
make[2]: *** [main/CMakeFiles/main.dir/main.cpp.o] Error 1
make[1]: *** [main/CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2 

发布阶段:

如何确保release文件夹中bin文件夹中的构建使用'path / release / lib'中的共享库?可能使用相对路径,如'../lib/'?

1 个答案:

答案 0 :(得分:0)

您必须将库的include目录添加到main/CMakeLists.txt。将其添加到shared_lib/CMakeLists.txt是不够的。试试这一行:

include_directories("../shared_lib/include")