如何link一个exe项目到类另一个exe项目

How to link an exe project to the classes in another exe project

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

如何让测试 class 访问其他 classes?

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

  include_directories(${otherExeProjectDir})

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

2) Link 使用其他项目的 obj 文件测试项目? 某种 add_library( otherclass.obj ) 疯狂?

3)

如果您的主要可执行源代码位置简单或平坦,那么类似这样的方法可能会起作用:

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>)

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