[CMake] How to test for the usability of a target

Johannes Zarl johannes.zarl at jku.at
Tue Oct 15 11:49:40 EDT 2013


Hi,

I'd like to make some code in my build system dependent on the existance of a 
target. Basically I'd like to write something like this:

if(TARGET optional_lib)
  add_library(bar ${bar_srcs})
  target_link_library(bar optional_lib)
endif()

The problem I have is that for a couple of reasons the CMakelists file for bar 
needs to be read before optional_lib. Therefore the "TARGET optional_lib" test 
fails even though I can link bar successfully against optional_lib.

As a simple test case, consider the following:

#CMakeLists.txt:
cmake_minimum_required ( VERSION 2.8.9 )
add_executable ( main ${CMAKE_CURRENT_SOURCE_DIR}/main.c )
target_link_libraries ( main foo )
if ( NOT TARGET foo )
    message("foo is not a target")
endif()
add_library(foo ${CMAKE_CURRENT_SOURCE_DIR}/foo.c)
##

#foo.c:
int FOO=23;
##

#main.c:
extern int FOO;
int main() {
  return FOO;
}
##

Running CMake on this project prints "foo is not a target", but main is built 
and linked successfully and correctly.

I'm currently working around the issue by letting the optional lib set a cache 
variable and testing for the variable instead of the target. Is there a way to 
actually get the information from the bulid system, or is this a hard limit of 
the CMake parser?

Cheers,
  Johannes


More information about the CMake mailing list