Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use file glob in a different directory in CMake

Tags:

cmake

file(GLOB ...) and file(GLOB_RECURSE ...) only seems to work on the current source directory. Is there any way to glob a different directory?

like image 922
Andreas Haferburg Avatar asked Dec 01 '16 06:12

Andreas Haferburg


People also ask

What does GLOB do in CMake?

GLOB will generate a list of all files that match the globbing expressions and store it into the variable. Globbing expressions are similar to regular expressions, but much simpler. If RELATIVE flag is specified for an expression, the results will be returned as a relative path to the given path.

Should I use GLOB CMake?

The creators of CMake themselves advise not to use globbing. (We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists. txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.)

What is a .CMake file?

A CMAKE file is a project file created by the open-source, cross-platform tool CMake. It contains source script in the CMake language for the entire program. CMake tool uses programming scripts, known as CMakeLists, to generate build files for a specific environment such as makefiles Unix machine.


2 Answers

file(GLOB) can be a little confusing at first, i had a similar issue a few months ago.

You have to specify your path directly in the <globbing-expressions> :

file(GLOB <variable>
     [LIST_DIRECTORIES true|false] [RELATIVE <path>]
     [<globbing-expressions>...])

For example :

file(GLOB my_cpp_list "${CMAKE_CURRENT_SOURCE_DIR}/directory/*.cpp")
foreach(file_path ${my_cpp_list})
    message(${file_path})
endforeach()

Will print the path of all .cpp files in ${CMAKE_CURRENT_SOURCE_DIR}/directory.

like image 196
Blabdouze Avatar answered Nov 09 '22 09:11

Blabdouze


I had the same issue where no matter what path I specified, I would get a glob from CMAKE_CURRENT_SOURCE_DIR. The issue was that the path I was providing to GLOB wasn't valid, and it was reverting (gracefully, but annoyingly) to CMAKE_CURRENT_SOURCE_DIR. For example, either of the following will create the symptom you see:

file(GLOB my_cpp_list "${CMAKE_CURRENT_SOURCE_DIR}/directory *.cpp")

I forgot the "/" after "directory". This was why I never got valid results, even with valid directory names.

file(GLOB my_cpp_list "${CMAKE_CURRENT_SOURCE_DIR}/directoryy/*.cpp")

There is no sub-folder named "directoryy"

like image 32
The Mawg Avatar answered Nov 09 '22 09:11

The Mawg