【问题标题】:Cmake Shared libraryCmake 共享库
【发布时间】:2016-02-16 14:19:29
【问题描述】:

我正在学习 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 中,我定义了项目设置和子目录。

根 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)

数学库(共享库)

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 

发布阶段:

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

【问题讨论】:

  • 您的可执行文件的名称是math,并且您正在尝试链接到一个名为main 的目标。这是笔误吗?
  • @HeyYO 谢谢,是的,这是一个错字。
  • use of undeclared identifier 是编译器错误,而不是链接器。您的包含有问题。您确定 math.h 在您的包含路径中吗?我假设这是声明 sum() 的文件。
  • 对了,math.h 是 C 标准数学库的名称。不要将此名称用于您自己的文件!
  • 它包括标准数学库。现在我把名字改成了my_math.h,找不到头文件

标签: makefile cmake


【解决方案1】:

您必须将库的包含目录添加到main/CMakeLists.txt。将其添加到 shared_lib/CMakeLists.txt 是不够的。试试这条线:

include_directories("../shared_lib/include")

【讨论】:

  • 不应该 Cmake 自动计算出该路径,因为我在 shared_lib/CMakeList.txt 中设置了include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
  • 没有。使用父 CMakeList.txt 文件不会将您的子 CmakeLists.txt 文件合并在一起。它们仍然是独立的项目。如果要声明一次包含,可以使用单个 CMakeList.txt 文件。
  • 这就是我想做的。例如,在顶级 CMakeLists.txt 中声明所有包含是一个好主意吗?
  • 我认为这不是一个好主意。您将项目分成单独的部分是有原因的。其中之一是更容易的依赖管理。当您将所有包含在一个文件中时,将不清楚哪个子项目取决于哪个。看看these answers,也许这就是你想要的。
  • 我需要的是shared_lib/CMakeLists.txt中的target_include_directories(mathLib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include),以便在编译main.cpp时可以访问它的头文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
相关资源
最近更新 更多