Michael IV
Michael IV

Reputation: 11496

CMake: "add_library IMPORTED" check if the lib exists

I am importing a static lib in CMAKE using add_library. The lib imports fine.But I also want to verify that.So I do this:

add_library(MYLIB STATIC IMPORTED)
set_target_properties(MYLIB PROPERTIES IMPORTED_LOCATION path/to/mylib.a)
#if(NOT  MYLIB)
  #  message(FATAL_ERROR "MYLIB library not found")
#endif()

It always returns false, even when the path is correct and the lib is imported ok.How can I check that the lib is imported?

Using Cmake 3.4.1

Upvotes: 3

Views: 2787

Answers (2)

Tsyvarev
Tsyvarev

Reputation: 66088

Command add_library() creates a target, not a variable.

Target existence can be checked with TARGET keyword:

add_library(MYLIB STATIC IMPORTED)
#...

if(NOT TARGET MYLIB)
   # Target is not exist
endif()

Note, that existence of the library target doesn't mean existence of the library file. Existence of the file should use EXISTS keyword:

if(EXISTS <path>)

Upvotes: 3

utopia
utopia

Reputation: 1535

Since you are failing/stopping processing anyway, then you could check it is imported by trying to use the library!

If you actually want to check before you import, then something like this may be appropriate:

find_library(MYLIB
  NAMES mylib
  PATHS
    path/to/mylib.a
  DOC "Find library mylib"
  NO_DEFAULT_PATH)

if(NOT MYLIB)
  message(FATAL_ERROR "MYLIB library not found")
endif()

You can remove NO_DEFAULT_PATH if you don't mind CMake looking in all the many default locations first before searching your stated PATHS.

Upvotes: 0

Related Questions