简体   繁体   中英

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

Suppose you want to do some unit testing on classes in an executable but you don't want to refactor them out into a lib where you can add the lib using target_link_libraries( target library ) in cmake.

How do you give the test class access to the other classes?

1) Build test project with the source files from the other project? another thing

  include_directories(${otherExeProjectDir})

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

2) Link test project with obj files from the other project? some sort of add_library( otherclass.obj ) craziness?

3)

If your main executable source locations are simple or flat, then something like this could work:

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

Otherwise the general solution is, unfortunately, to rely on some external information, eg top level source file locations or adding your own source properties to the main executable target.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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