如何更正我的 CMakeLists.txt 以便我的项目可以在 Linux 和 Windows 上构建?

问题描述 投票:0回答:1

我正在进行一个项目,最近添加了新功能和随附的单元测试。项目的结构如下所示:

Sim
└── models
    ├── otherModels
    └── myModel
        ├── CMakeLists.txt
        ├── model.cpp
        ├── model.h
        ├── test
        │   ├── CMakeLists.txt
        │   ├── geometryTest.cpp
        │   └── geometryTest.h
        └── util
            ├── CMakeLists.txt
            ├── geometry.cpp
            ├── geometry.h
            └── probability.h

总结问题

我的目标是能够在 Windows 和 Linux 上构建所述项目并执行单元测试。

实际结果

在 Windows 上,我能够构建项目并运行单元测试。

在 Linux 上,我收到构建错误,指出无法找到正在测试的库:

error while loading shared libraries: libmathUtil.so: cannot open shared object file: No such file or directory

预期结果

能够在 Linux 上构建。

我尝试过的事情

  1. 我用谷歌搜索了如何在Linux上查找文件并验证该文件是否存在:

    find . -name libmathUtil.so
    >>> ./build/make-Release/Sim/lib/libmathUtil.so
    
    
  2. 如果我注释掉,我就验证了一切都建立在Linux上

    add_subdirectory(test)

  3. 我尝试正确设置 CMakeLists.txt 文件,如下所示:

我的工作目录的顶级 CMake

set( target myCoolModel )

set( sources
    model.cpp
    )

set( headers
    model.h
    )

add_library( ${target} ${sources} ${headers} )

target_link_libraries( ${target}
    ${PROJECT_LIBRARIES}
    mathUtil
    )

# Group the target library into an IDE folder
set_target_properties( ${target} PROPERTIES FOLDER ${PROJECT_FOLDER} )

# Add the utility and test subdirectory 
enable_testing()
add_subdirectory( util )
add_subdirectory( test ) 

并且在

util
子目录中:

set( target mathUtil)
set( sources geometry.cpp )
set( headers geometry.h probability.h)

add_library( ${target} ${sources} ${headers} )

target_link_libraries( ${target} genMath::genMath )

target_compile_options( ${target} PRIVATE ${PROJECT_CXX_FLAGS} )

target_include_directories( ${target}
    PUBLIC  ${CMAKE_CURRENT_SOURCE_DIR} )

还有

test
目录:

enable_testing()

# Set target name, and dependencies
set( target modelTests )
set( sources geometryTest.cpp )
set( headers geometryTest.h)

# Find Google Test
find_package( GTest REQUIRED )

# Make test executable. 
add_executable( ${target} ${sources} ${headers} )

target_link_libraries(${target}
    mathUtil
    GTest::gtest_main
)

# Load GoogleTest and add these tests to the suite
include(GoogleTest)
gtest_discover_tests(${target})

# File unit tests into the project test folder (makes it easier to find in solution explorer)
set( PROJECT_FOLDER ${PROJECT_FOLDER}/test )
set_target_properties( ${target} PROPERTIES FOLDER ${PROJECT_FOLDER} )
c++ linux cmake googletest
1个回答
0
投票

所讨论的错误听起来像是在运行时发生的,而不是在构建时发生的。我会根据这个假设来回答:

文件

./build/make-Release/Sim/lib/libmathUtil.so
不在 LD_LIBRARY_PATH 指向的目录中,并且
modelTests
的 elf 标头缺少指向您的库的
RPATH
条目(可使用
readelf -d modelTests
进行验证,有关如何设置
 的文档) RPATH
在 cmake 这里)。

如果没有方法指导在何处查找正在使用的共享对象,则无法在运行时找到该库。

© www.soinside.com 2019 - 2024. All rights reserved.