Issue
I want a file that contains the build date to be build every time.
After some research I have tried many different approaches, but I don't understand them fully. I thought the following code should work, but it doesn't. It is written in a CMakeLists.txt
file which is part of many cascaded CMakeLists.txt
files.
[...]
add_library(${PROJECT_NAME} STATIC
src/software_version.cpp [...]
)
[...]
set(VERSION_FILE "src/software_version.cpp")
add_custom_target(build_software_version ALL COMMAND ${CMAKE_COMMAND} -E touch ${VERSION_FILE})
#or
add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E touch ${VERSION_FILE})
Edit:
I'm using the predefined __ DATE__ in a method in that file and I've found out that it wont be up-to-date if I don't build the file every time. If I just make a small change to the file so the file is beeing build again, the date is correct. I was hoping to achive that with the touch
command.
So I was expecting to see the note that the file was build in the build-log. (An other file shows up there every time too)
At this point the first command compiles, but doesn't change anything. The second one throws an error at building time.
[error]: https://i.stack.imgur.com/W5Cle.png
Solution
Your solution with add_custom_target
almost worked, there are just two things which need to be added:
- the custom target is run from the build directory... where no source file with that name is to be found. Prefixing
CMAKE_CURRENT_SOURCE_DIR
fixes that. It would also be possible to set theWORKING_DIRECTORY
parameter ofadd_custom_target
. - a dependency needs to be added as pointed out by Jarod42 in the comments.
I believe the following code does what you want:
add_custom_target(build_software_version
COMMAND ${CMAKE_COMMAND} -E touch src/software_version.cpp
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
add_library(${PROJECT_NAME} STATIC src/software_version.cpp)
add_dependencies(${PROJECT_NAME} build_software_version)
Some more thoughts
While the text above answers the question, it's not necessarily the best solution for the underlying problem. To have the current date compiled into the binary, I'd write the date into a file using CMake rather than relying on the __DATE__
preprocessor variable. If done right, this would force rebuilds only once per day.
Answered By - Friedrich Answer Checked By - Katrina (WPSolving Volunteer)