Get target filename without extension with CMake
Asked Answered
B

4

12

How can I get the basename of a target library with CMake?

I'm creating a library with the CMake variable name ${lib} as in

set(lib lib)
add_library(${lib} ...

I need the basename of the generated library file.

CMake will create a library with the filename <prefix>lib.<extension> where both <prefix> and <extension> are platform specific.

I've tried the generator $<TARGET_FILE_NAME:${lib}> which gives me the full name, which works because I'm needing this in a COMMAND, which is one of the few places where CMake allows generators.

To remove the extension using CMake I need to use GET_FILENAME_COMPONENT as in

GET_FILENAME_COMPONENT(<var> <filename> NAME_WE)

but this is used to set the variable <var> (in normal CMake fashion) and generators don't work there.

(The CMake language is an irregular abomination, if you ask me. CMake, as a concept, is pretty cool.)

Bobbysoxer answered 20/9, 2015 at 5:58 Comment(0)
R
5

I used get_property with get_filename_component and this worked for me:

get_property(lib_loc TARGET lib PROPERTY LOCATION)
get_filename_component(lib_we ${lib_loc} NAME_WE)
Ravioli answered 4/10, 2015 at 17:43 Comment(1)
This is deprecated since 2.8.12. Since the LOCATION is "guessed" when CMake is run. But you cannot fully know where the lib will end up until actual compile time. Therefore the use of $<TARGET_FILE> is the proper way. See CMP0026 for details.Okwu
A
3

If you don't want the prefix, you can simply do $<TARGET_FILE_BASE_NAME:${lib}>

e.g.

add_custom_target(
  create_txt
  DEPENDS ${lib}
  COMMAND ${CMAKE_COMMAND} -E touch $<TARGET_FILE_BASE_NAME:${lib}>.txt)

If you want the prefix, you can also do $<TARGET_FILE_PREFIX:${lib}>$<TARGET_FILE_BASE_NAME:${lib}>

e.g.

add_custom_target(
  create_txt
  DEPENDS ${lib}
  COMMAND ${CMAKE_COMMAND} -E touch $<TARGET_FILE_PREFIX:${lib}>$<TARGET_FILE_BASE_NAME:${lib}>.txt)
Anastomose answered 27/5, 2022 at 16:51 Comment(0)
I
2

Query the target's OUTPUT_NAME property:

get_target_property(_baseName lib OUTPUT_NAME)
Irascible answered 20/9, 2015 at 8:4 Comment(1)
"NOT FOUND" - this probably indicates that if you don't set it to anything (as in I want the default) it is empty?Bobbysoxer
C
0

cmake_path seems to do what you want:

set(path_to_mylib_a "/path/to/mylib.a")
cmake_path(GET path_to_mylib_a STEM mylib)
message("${mylib}")

Output:

mylib
Cavicorn answered 24/7, 2024 at 21:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.