YNW
YNW

Reputation: 21

CMake question: Link object file in a different directory

Please excuse if this is a newbie question. Searched online and haven't found a better solution.

The test.cpp is performing test and utilizes the class defined in Input.cpp. Linker complains as below: "ld.lld: error: undefined symbol: Input::parse()".

  1. Adding this line in the test/CMakeLists.txt works, but the code looks ugly.

    target_link_libraries(test ${PROJECT_SOURCE_DIR}/build/driver/CMakeFiles/Driver.dir/Input.cpp.o)

  2. Tried target_link_libraries(test Driver) and got the error message: (target_link_libraries): Target "Driver" of type EXECUTABLE may not be linked into another target.

    Here's a blurb from driver/CMakeLists.txt FYI

    add_executable(Driver main.cpp Input.cpp)

  3. Not sure if I can export Input.cpp.o in driver/CMakeLists.txt, then replace the target_link_libraries line with something like

    target_link_libraries(test Input)

Here is Directory Tree:

/CMakeLists.txt

/driver: CMakeLists.txt, main.cpp, Input.cpp, Input.hpp
   
/test: CMakeLists.txt

/test/gtest: test.cpp

/build/driver/CMakeFiles/Driver.dir/Input.cpp.o

Any input is much appreciated

Upvotes: 0

Views: 622

Answers (1)

fabian
fabian

Reputation: 82461

Move the Input.cpp file to a library. Both STATIC and OBJECT libraries should do the trick. The following cmake logic uses an OBJECT library, since it's closer to the first alternative in the question.

driver/CMakeLists.txt

add_library(driver_impl OBJECT Input.cpp Input.hpp)
add_executable(Driver main.cpp $<TARGET_OBJECTS:driver_impl>)

test/CMakeLists.txt

add_executable(Driver test.cpp $<TARGET_OBJECTS:driver_impl>)

Upvotes: 0

Related Questions