【问题标题】:How to link an exe project to the classes in another exe project如何将一个exe项目链接到另一个exe项目中的类
【发布时间】:2017-07-26 01:26:12
【问题描述】:

假设您想对可执行文件中的类进行一些单元测试,但又不想将它们重构到一个库中,您可以在其中使用 cmake 中的target_link_libraries( target library ) 添加该库。

如何让测试类访问其他类?

1) 使用其他项目的源文件构建测试项目? 另一件事

  include_directories(${otherExeProjectDir})

  set( SOURCE_FILES 
     main.cpp
     tests.h
     tests.cpp
     ${otherExeProjectDir}/otherclass1.h
     ${otherExeProjectDir}/otherclass2.h
   )

2) 将测试项目与来自其他项目的 obj 文件链接? 某种add_library( otherclass.obj ) 疯狂?

3)

【问题讨论】:

  • 我不明白你的问题。假设您的项目中有一个类,现在您想对该类进行单元测试。您需要做的只是包含该类的头文件并编写单元测试和单元测试的主要功能。
  • 两个项目:其他项目和测试项目。其他项目和测试项目一样有一个主要项目。如果我简单地包含它,测试项目将不知道在哪里寻找标题。
  • 我不明白。为什么不能只包括它。你没看到它在哪里吗?
  • 我说错了,如果您只是#include 一个标头,它仍然不知道实现在哪里,所以您最终会遇到 lnk2019 问题。

标签: c++ unit-testing cmake linker exe


【解决方案1】:

如果您的主要可执行源位置很简单或平坦,那么这样的方法可以工作:

cmake_minimum_required(VERSION 3.9)
project(tests)

# Get main executable source location properties
get_target_property(exe_sources exe SOURCES)
get_target_property(exe_source_dir exe SOURCE_DIR)

# Remove main entry point file
list(REMOVE_ITEM exe_sources main.cpp)

# Add test sources
add_executable(test1 test1.cpp)

# Add exe sources to test (assumes sources are relative paths)
foreach(src IN LISTS exe_sources)
  target_sources(test1 PRIVATE "${exe_source_dir}/${src}")
endforeach()

# Add exe include directories to test
target_include_directories(test1 PRIVATE 
  ${exe_source_dir}
  $<TARGET_PROPERTY:exe,INCLUDE_DIRECTORIES>)

否则,不幸的是,一般的解决方案是依赖一些外部信息,例如顶级源文件位置或将您自己的源属性添加到主可执行目标。

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 2012-12-25
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多