简体   繁体   English

用简单的C ++示例找不到库

[英]Cannot find library with simple C++ example

I am building a C++ library called alpha in Ubuntu with cmake, which contains one source file: 我正在使用cmake在Ubuntu中构建一个名为alpha的C ++库,其中包含一个源文件:

cmake_minimum_required(VERSION 2.8)

project(Alpha)

add_library (alpha alpha.cpp)

This creates a file called libalpha.a , which I now want to link to. 这将创建一个名为libalpha.a的文件,现在我想链接到该文件。 So, I copy it into the source directory of another C++ projected called beta , which also contains one source file: 因此,我将其复制到另一个名为beta C ++项目的源目录中,该项目还包含一个源文件:

cmake_minimum_required(VERSION 2.8)

project(Beta)

add_executable(beta beta.cpp)

target_link_libraries(beta alpha)

However, I get the following error: 但是,出现以下错误:

/usr/bin/ld: cannot find -lalpha

The same thing happens if I use the line: 如果使用该行,也会发生相同的事情:

target_link_libraries(beta libalpha.a)

Why can beta not find the alpha library? 为什么beta无法找到alpha库?

If you wish to build the library and the program completely separately, you have to use imported targets . 如果您希望完全分别构建库和程序,则必须使用导入的target When you try to link your executable against a "completely unknown" library, CMake build system automatically passes the task of locating the library to the linker, simply adding -lalpha option. 当您尝试将可执行文件链接到“完全未知”的库时,CMake构建系统会自动将查找库的任务传递给链接器,只需添加-lalpha选项即可。 When the linker encounters the option it attempts to locate libalpha.so in one of the standard library locations (ie /usr/lib/ , /usr/local/lib etc) and expectedly fails. 当链接器遇到该选项时,它将尝试在标准库位置之一(即/usr/lib//usr/local/lib等)中定位libalpha.so并预期失败。 You can use an absolute path to the libalpha.a : target_link_libraries(beta /path/to/libalpha.a) . 您可以使用libalpha.a的绝对路径: libalpha.a target_link_libraries(beta /path/to/libalpha.a)

However if you can build things together, this greatly simplifies the task. 但是,如果您可以一起构建事物,则可以大大简化任务。 Consider 考虑

<project>/CMakeLists.txt: <项目> /CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

Project(Test)

add_subdirectory(alpha)
add_subdirectory(beta)

<project>/alpha/CMakeLists.txt <项目> /alpha/CMakeLists.txt

cmake_minimum_required(VERSION 2.8.11)

project(alpha)

set(SOURCES alpha.c)

add_library(alpha ${SOURCES})
target_include_directories(
  alpha INTERFACE
  "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>"
  "$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>"
)

target_include_directories() with the complex expression within is required to automatically add libalpha include directories to all components which later are linked against libalpha. 要自动将libalpha包含目录添加到所有后来与libalpha链接的组件,需要使用target_include_directories()及其复杂的表达式。

<project>/beta/CMakeLists.txt <项目> /beta/CMakeLists.txt

project(beta)

set(SOURCES beta.c)

add_executable(beta ${SOURCES})
target_link_libraries(beta alpha)

将此行与alpha-library的路径一起添加。

link_directories( <library path> )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM