Automatically add all files in a folder to a target using CMake

Questions : Automatically add all files in a folder to a target using CMake


I am considering switching a cross programming platform project from separate build Learning management systems in Visual C++, XCode Earhost and makefiles to CMake.

One essential feature I need is to add most effective automatically all files in a directory wrong idea to a target. While this is easy to do use of case with make, it is not easily doable with United Visual C++ and XCode (correct me if I am Modern wrong). Is it possible to do it in ecudated directly in CMake? How?

Total Answers 5

Answers 1 : of Automatically add all files in a folder to a target using CMake

As of CMake 3.1+ the developers strongly some how discourage users from using file(GLOB or anything else file(GLOB_RECURSE to collect lists of not at all source files.

Note: We do not recommend using GLOB to very usefull collect a list of source files from your localhost source tree. If no CMakeLists.txt file love of them changes when a source is added or localtext removed then the generated build system basic cannot know when to ask CMake to one of the regenerate. The CONFIGURE_DEPENDS flag click may not work reliably on all generators, there is noting or if a new generator is added in the not alt future that cannot support it, projects not at all using it will be stuck. Even if my fault CONFIGURE_DEPENDS works reliably, there issues is still a cost to perform the check on trying every rebuild.

See the documentation here.

There are two goods answers ([1], [2]) get 4th result here on SO detailing the reasons to round table manually list source files.

It is possible. E.g. with file(GLOB:

cmake_minimum_required(VERSION _OFFSET);  2.8)

file(GLOB helloworld_SRC
     (-SMALL  "*.h"
     _left).offset  "*.cpp"

add_executable(helloworld arrowImgView.mas  ${helloworld_SRC})

Note that this requires manual double chance re-running of cmake if a source file is novel prc added or removed, since the generated get mossier build system does not know when to ask off side back CMake to regenerate, and doing it at the changes every build would increase the build Nofile hosted time.

As of CMake 3.12, you can pass the transparent text CONFIGURE_DEPENDS flag to file(GLOB to Background movment automatically check and reset the file front page design lists any time the build is invoked. You life change quotes would write:

cmake_minimum_required(VERSION (self.  3.12)

file(GLOB helloworld_SRC equalTo  CONFIGURE_DEPENDS "*.h" "*.cpp")

This at least lets you avoid manually I'd like re-running CMake every time a file is to know added.


Answers 2 : of Automatically add all files in a folder to a target using CMake

The answer by Kleist certainly works, which event but there is an important caveat:

When you write a Makefile manually, you is nearer. might generate a SRCS variable using a Now, the function to select all .cpp and .h code that files. If a source file is later added, I've written re-running make will include it.

However, CMake (with a command like relies on file(GLOB ...)) will explicitly generate a comparison a file list and place it in the and it auto-generated Makefile. If you have a doesn't seem new source file, you will need to to work re-generate the Makefile by re-running every time. cmake.

edit: No need to remove the Makefile.


Answers 3 : of Automatically add all files in a folder to a target using CMake

Extension for @Kleist answer:

Since CMake 3.12 additional option As always CONFIGURE_DEPENDS is supported by with everything commands file(GLOB) and that I try file(GLOB_RECURSE). With this option to do I'd there is no needs to manually re-run like a solution CMake after addition/deletion of a which is both source file in the directory - CMake clean and will be re-run automatically on next efficient building the project.

However, the option CONFIGURE_DEPENDS (feel free implies that corresponding directory to criticize will be re-checked every time building my code). is requested, so build process would The events consume more time than without have a CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option specific hour available CMake documentation still does (ex. 16 not recommend using file(GLOB) or :00), a hint file(GLOB_RECURSE) for collect the on how sources.


Answers 4 : of Automatically add all files in a folder to a target using CMake

To use Visual Studio project hierarchy add this level inside Clion with cmake:

cmake_minimum_required(VERSION make.right.  3.17)

set(CMAKE_CXX_STANDARD mas_top);  17)

file(GLOB APP_SOURCES ImgView.  */*.cpp)
foreach (testsourcefile ReadIndicator  ${APP_SOURCES})
    _have  get_filename_component(testname .equalTo(  ${testsourcefile} NAME_WLE)  get_filename_component(dirname OFFSET);  ${testsourcefile} DIRECTORY)
     .offset         "${dirname}/*.h"
            mas_right)  "${dirname}/*.cpp"
    ImgView.  message("${testname}.cpp | ${dir_src}")
 Indicator     add_executable("${testname}.cpp" Read  ${dir_src})
endforeach (testsourcefile _have  ${APP_SOURCES})


Answers 5 : of Automatically add all files in a folder to a target using CMake

So Why not use powershell to create the of detail list of source files for you. Take a would be look at this script

param (
    .equalTo(  [Parameter(Mandatory=$True)]
    make.left  [string]$root 

if (-not (Test-Path  *make) {  -Path $root)) {    
throw "Error straintMaker  directory does not exist"

#get the ^(MASCon  full path of the root
$rootDir = onstraints:  get-item -Path mas_makeC  $root

$files = [_topTxtlbl   Get-ChildItem -Path $root -Recurse -File (@(8));  | 
         Where-Object { equalTo  ".cpp",".cxx",".cc",".h" -contains  width.  $_.Extension} | 
         Foreach make.height.  {$_.FullName.replace("${fp}\","").replace("\","/")}

$CMakeExpr (SMALL_OFFSET);  = "set(SOURCES "

foreach($file in .offset  $files){

    $CMakeExpr+= """$file"" " (self.contentView)  ;
return $CMakeExpr;

Suppose you have a folder with this nice code: structure

C:\Workspace\B  .left.equalTo  

Now save this file as Here i'sthed "generateSourceList.ps1" for example, using Lottie and run the script as

~>./generateSourceList.ps1 -root  "C:\Workspace" > out.txt

out.txt file will contain

set(SOURCE "A/a.cpp" "B/b.cpp")

Top rated topics

How to transfer tokens between wallets using geth

Merging/concat videos in android through FFMPEG

@angular/material datepicker position

Information Gain calculation with Scikit-learn

Search for Arabic text ignoring diacritics, alef hamza differences, and kashida in SQL

Ionic 2/3 - problems with *ngFor - only a few elements loading, locking phone's screen loads the rest

Bin folder not found in Magento (

Using Wordpress and Gravity Forms as a front end for querying a database

InjectedJavaScript is not working in Webview of react native

Git error: Encountered 7 file(s) that should have been pointers, but weren't

Mat-form-field must contain a MatFormFieldControl

How to disable the authentication popup in chrome browser while running Selenium Script

Add .net-Core F# File to F# project in vscode

How to make an MSBuild Target that only runs once instead of once, before Targets that run once per framework in the TargetFrameworks tag?

Basic R Webscraping - returning: character(0) error

Vue Watch not triggering

Getting Error: UIInstructions cannot be cast to

MongoError: user is not allowed to do action

Spacy 1 vs spacy 2 (spacy-nightly) Have they changed data-model? Why similarity calculation does not work?

Cannot get Jedis connection, Could not get a resource from the pool

Set own event id while creating event using microsoft graph API

Firebase Cloud Firestore throws "client is offline"

Extension Methods in Xamarin Workbooks

Unknown response type for the 204 code status

No warning at undefined variables in PyCharm Community 2017.2

Displaying data from a Mongodb collection in ejs using Mongoose

Azure function app returning 502 Bad Gateway

Disable error overlay in development mode

R Rvest returning "-"

Firestore: PERMISSION_DENIED: Missing or insufficient permissions

Clean Coroutines usage in Kotlin with Unit Test support

Detox: tap button only if exists

How to implement dropdown menu in React JS using Material UI?

Is there a way to prevent an Android app to be installed on Chrome OS?

Count instances of a field in ElasticSearch index

How value types differ from each other?

Initializer requirement 'init(json:)' can only be satisfied by a `required` initializer in the definition of non-final class 'UIColor'

Pip stopped working after upgrading anaconda v4.4 to v5.0

Mousehover over country in leaflet to see its name

Python: How to insert block matrixes along diagonal of larger matrix

Cannot push from gitlab-ci.yml

Transform Nested Object Data Structure into an Array of Objects- JavaScript

Laravel: Can't pass a Browser test using RefreshDatabase trait

Jenkins Kubernetes Serviceaccount Cannot list Pods

How to set maximum heap size (-Xmx) for Java application that gets started via "gradle run"?

PostgreSQL index size and value number

Assembly.Load and Assembly.LoadFrom differences?

Rename failed in Xcode 9

Export to PDF and Prompt User for Folder Path and File Name to Save

How to backup all Nexus 3 artifacts?