Reputation: 1569
I have this variable set in the root CMakeLists.txt
set(${LIBNAME}_srcs
File1.cpp
File2.cpp
File3.cpp
File4.cpp
File5.cpp
)
add_subdirectory(A)
and I want to add the variable as a source for the executable in the subdirectory A
add_executable(${TEST}}
What is the cleanest way to do this? without having to create a new variable with ../ on all the source files? Or is there a macro I can use?
Upvotes: 1
Views: 1227
Reputation: 78448
You can insert the absolute path to each of the values in ${LIBNAME}_srcs
by doing something like:
foreach(${LIBNAME}_src ${${LIBNAME}_srcs})
list(APPEND abs_${LIBNAME}_srcs ${CMAKE_SOURCE_DIR}/${${LIBNAME}_src})
endforeach()
add_executable(${TEST} ${abs_${LIBNAME}_srcs})
Jumping to conclusions here, it looks like what you're doing may be a bit unusual.
Normally the add_executable
call would be made in the same place where the list of source files is gathered - usually in the same directory.
Going by the fact that you've named your sources variable ${LIBNAME}_srcs
, I'd guess that you're already creating a library from these sources. If so, it'd be better to just link that library in your test subdirectory rather than recompiling all the library's sources into the executable.
Something like:
add_executable(${TEST} test_main.cpp)
target_link_libraries(${TEST} ${LIBNAME})
Upvotes: 2
Reputation: 48815
When I add sources, I do something like this:
set(${LIBNAME}_srcs
${SRC}/File1.cpp
${SRC}/File2.cpp
${SRC}/File3.cpp
${SRC}/File4.cpp
${SRC}/File5.cpp
)
Where ${SRC}
is the absolute path to the source directory found using ${CMAKE_SOURCE_DIR}
.
Then, you can simply use add_executable(${TEST} ${LIBNAME}_srcs)
in your subdirectory. CMake will automatically import the scope of parent directories into child directories.
Upvotes: 0