如何为模块化项目正确创建CMake文件

如何为模块化项目正确创建CMake文件

本文介绍了如何为模块化项目正确创建CMake文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设C ++项目A是我的主程序,项目B是我的共享对象(.so)的模块.项目A包含两个项目之间通用的源和标头.在运行时项目一个加载模块.so文件.

Suppose C++ project A as my main program and project B is my module that is shared object (.so). Project A consist source and headers that is common between both projects. Project A load module .so file in runtime.

项目A:

class-AI.cpp (It contains function funcA)
class-AI.h

class-AII.cpp
class-AII.h

class-AIII.cpp
class-AIII.h

main.cpp

项目B :(共享对象)

class-BI.cpp (Its inherit from class-AI)
class-BI.h

使用以下CMake文件,两个项目均成功构建.

With following CMake files both project build successfully.

项目CMake文件:

cmake_minimum_required(VERSION 3.6)
project(ProjectA)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES
        main.cpp
        class-AI.cpp
        class-AI.h
        class-AII.cpp
        class-AII.h
        class-AIII.cpp
        class-AIII.h)

add_executable(ProjectA ${SOURCE_FILES})

set(EXECUTABLE_OUTPUT_PATH /opt/ProjectA/bin/)

项目B CMakefile:

cmake_minimum_required(VERSION 3.6)
project(ProjectB)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES class-BI.cpp class-BI.h)
add_library(ProjectB SHARED ${SOURCE_FILES})
set_target_properties(ProjectB PROPERTIES
        PREFIX ""
        LIBRARY_OUTPUT_DIRECTORY /opt/ProjectA/bin/)

但是在运行时,项目将出现以下错误:

But at runtime Project A following error will be appear:

undefined symbol: _ZN6class-AI4funcAEv

如何使用CMake文件将依赖项正确添加到项目B并解决此错误? (实际上,我想将我的netbeans C ++项目更改为Jetbrains CLion)

How can I add dependency to project B correctly using CMake file and solve this error? (Actually I want to change my netbeans C++ project to Jetbrains CLion)

推荐答案

感谢 Florian for .通过将以下行添加到Project A CMake文件中,我的问题得以解决:

Thanks to Florian for his comment. My problem solved with adding this lines to Project A CMake file:

add_library(ProjectB SHARED IMPORTED GLOBAL)
set_target_properties(ProjectB PROPERTIES IMPORTED_LOCATION "/opt/ProjectA/bin/ProjectB.so")
target_link_libraries(ProjectA ProjectB)

这篇关于如何为模块化项目正确创建CMake文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:43