Little trick to get the latest build time as a variable in your c project

greg-dickson
Posts: 37
Joined: Sun Nov 01, 2020 1:51 am

Little trick to get the latest build time as a variable in your c project

Postby greg-dickson » Fri Feb 07, 2025 4:19 am

Hi

I code in C so C++ may be a little different.
Also I am on linux so for others the COMMAND line will be different

Anyway I wanted a base timeline that was the absolute last build time every time I compiled
other methods give the last full compile time which can be quite old.
I also wanted it in UTC
The command line in linux that produces this value is

Code: Select all

date -u +%s
*
* Add this to projects CMakeLists.txt
*

Code: Select all

#define the build_time.c filename and path
set(BUILD_TIME_FILE "${CMAKE_CURRENT_SOURCE_DIR}/main/build_time.c")

# Ensure the file exists, otherwise generate an initial version
if(NOT EXISTS ${BUILD_TIME_FILE})
  file(WRITE ${BUILD_TIME_FILE} "const unsigned int Build_time_unix = 0;\n")
endif()

# Custom target to generate build_time.c on each build
add_custom_target(generate_build_time ALL
  COMMAND /bin/sh -c "echo 'const unsigned int Build_time_unix = '$(date -u +%s)';' > ${BUILD_TIME_FILE}"
  COMMENT "Generating build_time.c with current UTC timestamp"
  VERBATIM
)
* Then add this to bottom of your main/CMakeLists.txt adding build_time.c to your SRCS as well

Code: Select all

idf_component_register(SRCS  "build_time.c" .......)
add_dependencies(${COMPONENT_LIB} generate_build_time)
your header file then only needs to have this line above where you retrieve the variable

Code: Select all

extern const unsigned int Build_time_unix;

you can then simply go

Code: Select all

time_t built = (time_t) Build_time_unix;
and voila

Have fun.

Who is online

Users browsing this forum: No registered users and 170 guests