7

So I have:

get_filename_component(a_dir ${some_file} PATH)
get_filename_component(a_last_dir ${a_dir} NAME)

In which a_last_dir should return the lowest level of my directory and a_dir should return my full directory.

Anyway I can make a_second_last_dir possible?? To return the second-lower level of the full directory?

  • By appending `..`? E.g. `get_filename_component(a_second_last_dir "/some/dir/sub/../.." ABSOLUTE)` – Florian Dec 15 '15 at 19:51
  • I don't have the full directory available to add `..`... –  Dec 15 '15 at 20:39
  • Can you give an example of a directory name and what part you want to extract? Are we talking about something like [here](http://stackoverflow.com/questions/28348309/in-python-how-should-one-extract-the-second-last-directory-name-in-a-path)? CMake's [`string()`](https://cmake.org/cmake/help/v3.4/command/string.html) command also allows for a lot of things. – Florian Dec 15 '15 at 21:00
  • Managed to make it work. I use directory of directory twice so that I can get the parent name :D Not a beautiful solution but it works :P –  Dec 15 '15 at 21:52
  • I still think you can use `../..`. Please see my answer below. – Florian Dec 16 '15 at 11:54

1 Answers1

10

Turning my comments into an answer

You can use get_filename_component() by appending ../...

I understand your current solution to look like this:

cmake_minimum_required(VERSION 2.8)

project(SecondLastDirName)

set(some_file "some/dir/sub/some_file.h")

get_filename_component(a_dir "${some_file}" PATH)
get_filename_component(a_last_dir "${a_dir}" NAME)

get_filename_component(a_second_dir "${a_dir}" PATH)
get_filename_component(a_second_last_dir "${a_second_dir}" NAME)

message("a_second_last_dir = ${a_second_last_dir}")

Which gives a_second_last_dir = dir as an output.

You can get the same output with:

get_filename_component(a_second_dir "${some_file}/../.." ABSOLUTE)
get_filename_component(a_second_last_dir "${a_second_dir}" NAME)

message("a_second_last_dir = ${a_second_last_dir}")

The intermediate a_second_dir path could be an invalid/non-existing path (since CMAKE_CURRENT_SOURCE_DIR is prefixed), but I think it does not matter here.

If you want it to be a correct absolute path, you should prefix the correct base dir yourself (or see CMake 3.4 which introduced BASE_DIR option to get_filename_component(... ABSOLUTE)).

Florian
  • 39,996
  • 9
  • 133
  • 149