Link a Target to a custom built library

I have a target executable, app. Which I am trying to link to a libFoo.a, which is not built by CMake, but can be built by invoking a script, build.sh. Is there a way I can link app to a custom built libFoo.a?

I’ve tried the following…

add_custom_command(
   OUTPUT libFoo.a
   COMMAND build.sh)

add_libary(Foo STATIC IMPORTED GLOBAL) # Not sure if GLOBAL is necessary
set_target_properties(Foo PROPERTIES IMPORTED_LOCATION libFoo.a)

add_executable(app main.cpp)

target_link_libraries(app
   Foo # or libFoo.a
)

But I often get the error that there is No rule to make target libFoo.a I’ve played around with pathing around libFoo.a (output in BINARY_DIR, explicitly specificying paths), but can’t seem to accomplish what I’m looking for. Any recommendations or a better approach to take?

A custom command is not sufficient, you also need a target that depends on the output of this custom command, e.g. a custom target, and then a target level dependency between that target and the consuming target.

Adding this in there should help:

add_library(FooReal INTERFACE)
add_dependencies(FooReal libFoo.a)
target_link_libraries(FooReal INTERFACE Foo)

I’d also recommend using absolute paths for libFoo.a.

Can you give a bit more context? I tried out your suggestion to get the following…

add_custom_command(
   OUTPUT libFoo.a
   COMMAND build.sh)

add_libary(Foo STATIC IMPORTED GLOBAL) # Not sure if GLOBAL is necessary
set_target_properties(Foo PROPERTIES IMPORTED_LOCATION libFoo.a)

add_library(FooReal INTERFACE)
add_dependencies(FooReal libFoo.a)
target_link_libraries(FooReal INTERFACE Foo)

add_executable(app main.cpp)

target_link_libraries(app
   FooReal
)

but I still get the following error, No rule to make target 'libFoo.a', needed by 'app'.

I ended up finding this question on Stack Overflow, custom target as a target library in cmake - Stack Overflow.

With this I ended up using this pattern, which worked.

add_custom_command(
   OUTPUT libFoo.a
   COMMAND build.sh)

add_custom_target(buildLibFoo DEPENDS libFoo.a)

add_libary(Foo STATIC IMPORTED GLOBAL) # Not sure if GLOBAL is necessary
add_dependencies(Foo builLibFoo)
set_target_properties(Foo PROPERTIES IMPORTED_LOCATION libFoo.a)

add_executable(app main.cpp)

target_link_libraries(app
   Foo
)

@ben.boeckel, I’d still be curious what your solution would have looked like.

The IMPORTED_LOCATION property should be an absolute path to libFoo.a here I believe.