Reputation: 10050
I'm trying to compile executable files in a subdirectory project/model/tests
for testing and need to link my model files which reside at project/model
. However, I can't get it to work. I've successfully added the parent directory but cmake keeps telling me no source file found for foo.cpp, which is in the parent directory, while bar.cpp, which is in the current directory, is added correctly.
cmake_minimum_required(VERSION 2.6)
# get parent directory
get_filename_component(MODEL_DIR ${CMAKE_CURRENT_SOURCE_DIR} PATH)
# Locate GTest
find_package(GTest REQUIRED)
# Add parent directory
include_directories(${GTEST_INCLUDE_DIRS} ${MODEL_DIR})
link_directories(${MODEL_DIR})
# all included directories are printed out correctly
get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES)
foreach(dir ${dirs})
message(STATUS "dir='${dir}'")
endforeach()
# foo.cpp, which is in the parent directory is not found
add_executable(runTests foo.cpp bar.cpp)
target_link_libraries(runTests ${GTEST_LIBRARIES} pthread)
Thank you.
Upvotes: 2
Views: 4856
Reputation: 171117
When files listed in add_executable()
and add_library()
are given as relative paths (which they almost always are), they are interpretedd relative to CMAKE_CURRENT_SOURCE_DIR
. In other words, you have to do one of these:
add_executable(runTests ../foo.cpp bar.cpp)
Or:
add_executable(runTests ${MODEL_DIR}/foo.cpp bar.cpp)
Side note: it's almost never a good idea to use link_directories()
; that command is genrally more trouble than it's worth. The preferred alternative is to provide full paths to target_link_libraries()
where necessary.
Upvotes: 11