One project I work on used to add a __FILENAME__
macro definition when the generator used was GNU Make, as follows:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__FILENAME__='\"$(notdir $(abspath $<))\"'")
This is similar to how one would do it directly in a Makefile by setting CFLAGS
or CXXFLAGS
to -D__FILENAME__='"$(notdir $(abspath $<))"'
.
This made __FILENAME__
similar to __FILE__
, but kept only the base file name, so that code like this:
// this is in src/main.c
printf("__FILE__ %s\n", __FILE__);
printf("__FILENAME__ %s\n", __FILENAME__);
will output:
__FILE__ /path/to/project/src/main.c
__FILENAME__ main.c
This worked with older versions of CMake: 3.12, 3.16, and 3.18. After an update to 3.20 the second line becomes __FILENAME__ compiler_depend.ts
. This happens even if cmake_minimum_required
is set to 3.16 when using 3.20.
compiler_depends.ts
is a file generated by CMake and as far as I’m aware it wasn’t previously generated.
Here’s a minimal example:
cmake_minimum_required(VERSION 3.16)
project(example)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__FILENAME__='\"$(notdir $(abspath $<))\"'")
add_executable(exe src/main.c)
Looking at the files generated, compiler_depends.ts
appears in a single place: in CMakeFiles/exe.dir/build.make
:
# Include the compile flags for this target's objects.
include CMakeFiles/exe.dir/flags.make
CMakeFiles/exe.dir/src/main.c.o: CMakeFiles/exe.dir/flags.make
CMakeFiles/exe.dir/src/main.c.o: ../src/main.c
CMakeFiles/exe.dir/src/main.c.o: CMakeFiles/exe.dir/compiler_depend.ts
I first suspected that flags.cmake
looks different, but it doesn’t.
I know that messing with CMAKE_C_FLAGS
like this is not necessarily portable, or good-style, but is this a bug in CMake and how the build files are generated?
EDIT: After thinking a bit more about this, just because something works with Make it doesn’t mean that it should work when using CMake to generate makefiles. Even with Make, you still end up with broken builds/unexpected behaviors if you append to CFLAGS
after doing this. I’m only thinking that this could be considered a bug because it breaks something that used to work with older versions, even if cmake_minimum_required
asks for an older version. At the same time I don’t see how a policy could be introduce to keep this behavior, as it is something really fragile that can break at any time due to someone appending something to CMAKE_C_FLAGS
.