[CMake] CMAKE way to get leaf of file path

Alexander Neundorf a.neundorf-work at gmx.net
Mon Nov 8 14:59:04 EST 2010


On Monday 08 November 2010, Russell L. Carter wrote:
> On 11/07/2010 01:49 AM, Michael Hertling wrote:
> > On 11/07/2010 02:07 AM, Russell L. Carter wrote:
> >> Hi there,
> >> Happy cmake user here.  I want to retrieve the leaf name of
> >> the directory property "PARENT_DIRECTORY".  This is really
> >> a more general cmake question:  how do I most efficiently
> >> manipulate path components of the absolute pathnames that
> >> cmake uses and returns for many variables?
> >>
> >> In the current case, suppose I have
> >>
> >> "/home/me/project/src/module/help"
> >>
> >> how do I, in the best CMAKE WAY, extract the leaf, "help"?
> >>
> >> string(REGEXP) or something like that?
> >>
> >> I would love to be able to run a bash script on the full
> >> path and return just the leaf...  can I do that?
> >
> > You might try STRING(REGEX REPLACE "^.*/([^/]*)\$" "\\1" LEAF ${PATH}),
> > but also read about FILE(TO_CMAKE_PATH ...), FILE(TO_NATIVE_PATH ...)
> > and GET_FILENAME_COMPONENT().
>
> That STRING(REGEX ...) got me closer to what I want, but I eventually
> settled on this approach (suggested by an email from several years
> ago:
>
> string(REPLACE "/" ";" p2list "${path}")
> list(REVERSE p2list)
> list(GET p2list 0 first)
> list(GET p2list 1 second)
> message(STATUS "first: ${first} second: ${second}")
>
> Now I can automatically generate unique names for tests by location in
> the hierarchy.  Awesome.


To get the last component of a path, use
get_filename_component(... NAME)
To get the parent directory, use
get_filename_component(... PATH)


When you need to generate a unique name from a path, you could use the 
STRING() command to replace all "/" with e.g. an underscore.

Alex


More information about the CMake mailing list