简体   繁体   中英

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_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. So, I copy it into the source directory of another C++ projected called beta , which also contains one source file:

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?

If you wish to build the library and the program completely separately, you have to use imported targets . 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. 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. You can use an absolute path to the 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:

cmake_minimum_required(VERSION 2.8)

Project(Test)

add_subdirectory(alpha)
add_subdirectory(beta)

<project>/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.

<project>/beta/CMakeLists.txt

project(beta)

set(SOURCES beta.c)

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

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

link_directories( <library path> )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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