简体   繁体   English

如何在 CMake 中交叉链接库

[英]How to cross link libraries in CMake

In a c++ CMake project I have an executable main and two libraries lib1 and lib2 .在 c++ CMake 项目中,我有一个可执行的main和两个库lib1lib2 A function in lib1 needs a function from lib2 and visa versa. lib1 中的lib1需要 lib2 中的lib2 ,反之亦然。 Also, lib1 only contains .h files.此外, lib1仅包含.h文件。 The main executable will use both libraries. main可执行文件将使用这两个库。 When I try and "make" the project, I get an error:当我尝试“制作”项目时,出现错误:
error: redefinition of 'void lib1()'.
The file structure looks somewhat like this文件结构看起来有点像这样

/path/to/my/project
├── CMakeLists.txt # Project directory
├── main.cpp
├── Lib1
│   ├── ...files (.h only)...
│   ├── CMakeLists.txt # lib1 cmake
├── Lib2
│   ├── ...source files (.cpp & .h)...
│   ├── CMakeLists.txt # lib2 cmake

The CMakeLists.txt in the Project directory includes the following: Project 目录下的 CMakeLists.txt 包括以下内容:

add_executable(${PROJECT_NAME} main.cpp)

add_subdirectory(Lib1)
add_subdirectory(Lib2)

target_link_libraries(${PROJECT_NAME}
  lib2
  lib1
)

The CMakeLists.txt in the Lib1 directory includes the following: Lib1目录下的CMakeLists.txt包括以下内容:

add_library(lib1 INTERFACE)

target_include_directories(lib1
    INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
)

target_link_libraries(lib1 INTERFACE
    lib2
)

The CMakeLists.txt in the Lib2 directory includes the following: Lib2目录下的CMakeLists.txt包括以下内容:

add_library(lib2 ${SOURCES} ${HEADERS}) # SOURCES and HEADERS set in lines above

target_include_directories(lib2
    INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
)

target_link_libraries(lib2 
    lib1
)

If I had to guess, the issue is it is trying to import lib1 headers twice.如果我不得不猜测,问题是它试图两次导入 lib1 标头。 Once from lib2 and once in my main executable.一次来自 lib2,一次在我的main可执行文件中。 How do I link the libraries so that isn't an issue?我如何链接库,这样这不是问题?

I dont think it's anything related to cmake.我认为这与 cmake 无关。 Although convoluted (I'd do it in another way but hey it's your code) I think you are defining the body of a function in lib1 where it should reside in a cpp file.虽然令人费解(我会以另一种方式做,但嘿,这是你的代码)我认为你在 lib1 中定义了 function 的主体,它应该驻留在 cpp 文件中。

Make that function lib1 inline.使 function lib1内联。

inline void lib1() {
...
}

or alternatively defined it in the header and implement it in a body file或者在 header 中定义它并在正文文件中实现它

//lib1.h
void lib1(); 

Then然后

//lib1.cpp
#include "lib1.h"
void lib1() {
...
}

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

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