CMake - How to get the SECOND LAST in the director

2019-06-21 01:17发布

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?

标签: cmake
1条回答
Animai°情兽
2楼-- · 2019-06-21 01:34

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)).

查看更多
登录 后发表回答