How to link executable with object created in another CMakeLists.txt in the same project?

My project builds multiple programs in different directories. E.g. suppose the project includes source files in src/progA and src/progB, and there is a CMakeLists.txt file in each of those directories. Further suppose that progB should be linked with an object file corresponding to progA_module.c that’s generated while building progA. How do I portably specify the location of progA_module.c.o in progB/CMakeLists.txt? Something like this, where “CMAKE_SOMETHING_SOMETHING” is actually a standard cmake variable or generator expression?

# Link progB with an object generated for the progA target
set(PROGA_OBJ ${CMAKE_SOMETHING_SOMETHING}/progA_module.c.o)

add_executable(progB
               ${PROGA_OBJ}
               <other stuff here…>)

On my ubuntu system I see that the generated progA_module.c.o is in build/src/progA/CMakeFiles/progA.dir/progA_module.c.o - but I suspect it’s a bad idea to hard-code this path in progB/CMakeLists.txt. How should this location be specified in a portable way?

It seems like you want an OBJECT library. With those, their objects are included in any target using them (directly) via target_link_libraries.

1 Like