how to cleanup random byproducts

i have several files with a random counter in the filename that i want to remove on clean.

add_custom_target(foo ALL
	COMMAND           ${CMAKE_COMMAND} -E touch afile{1..3}.bar
	BYPRODUCTS
		*.bar
)

however, CMake does not allow wildchars, every byproduct must be set explicitly. I am using Makefile generator. Maybe i can glob a list of files and mark them as generated, or add them as additional clean files.

What is the best way to do it?

Update: semi working solution:

add_custom_target(foo ALL
	COMMAND ${CMAKE_COMMAND} -E touch afile{1..3}.bar
)

file( GLOB barlist CONFIGURE_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/*.bar" )
set_target_properties(foo PROPERTIES ADDITIONAL_CLEAN_FILES "${barlist}")

The file list on glob is updated before COMMAND is executed, therefore contains the set of files from the previous build.

Globs are not supported in Ninja, so you’ll need to explicitly list the names of the created byproduct files.

1 Like

I am not familiar with Ninja. It seems to be working. I can observe the following:

there are no afilen.bar files at first
then i build the project
the files were generated
then i clean the project
no afilen.bar files after that

Here is the build output:

user@machine: $ ls -l src/*.bar
ls: cannot access 'src/*.bar': No such file or directory
user@machine: $ ninja
[0/2] Re-checking globbed directories...
-- GLOB mismatch!
[1/2] Re-running CMake...
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/build
[0/2] Re-checking globbed directories...
[1/1] cd /home/user/src && /snap/cmake/858/bin/cmake -E touch afile{1..5}.bar
user@machine: $ ls -l src/*.bar
-rw-rw-r-- 1 user user 0 Apr 15 15:22 src/afile1.bar
-rw-rw-r-- 1 user user 0 Apr 15 15:22 src/afile2.bar
-rw-rw-r-- 1 user user 0 Apr 15 15:22 src/afile3.bar
-rw-rw-r-- 1 user user 0 Apr 15 15:22 src/afile4.bar
-rw-rw-r-- 1 user user 0 Apr 15 15:22 src/afile5.bar
user@machine: $ ninja clean
[0/2] Re-checking globbed directories...
-- GLOB mismatch!
[1/2] Re-running CMake...
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/build
[0/2] Re-checking globbed directories...
[2/2] Cleaning all built files...
Cleaning... 0 files.
user@machine: $ ls -l src/*.bar
ls: cannot access 'src/*.bar': No such file or directory
user@machine: $ 

Edit: it seems to work reliably with Ninja but not with Unix Makefile. In both generators when i read out target property ADDITIONAL_CLEAN_FILES after set_target_properties it always shows for the glob list for the previous build.

Yes, this makes sense. The globbing is done at CMake configure time. If that changes, the glob is likely to be inaccurate in the future (e.g., a new .bar file is made during the build by some other process.