You're welcome! Let's modify the CMake logic so that:
- Before each
cmake --build, the external script gen_id.sh is executed.
- If
somefile.id changes as a result of running the script, then:
- CMake reconfigures (because we'll make it depend on
somefile.id)
foo.c gets recompiled with the new -DVAR=<value>
This will be done without introducing a header file and keeping the use of -DVAR=....
✅ Final Goal
- Run
gen_id.sh before build
- Only rebuild
foo.c if somefile.id changed
- Pass content of
somefile.id to foo.c via -DVAR=<value>
✅ Updated CMakeLists.txt
# ---- CMakeLists.txt -------------------------------------------------------
cmake_minimum_required(VERSION 3.16)
project(demo C)
set(ID_FILE "${CMAKE_SOURCE_DIR}/somefile.id")
set(GEN_SCRIPT "${CMAKE_SOURCE_DIR}/gen_id.sh")
# 1) Create a custom target that runs gen_id.sh before building anything else
add_custom_target(run_gen_script
COMMAND ${CMAKE_COMMAND} -E env SHELL=/bin/bash ${GEN_SCRIPT}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMENT "Running gen_id.sh to update somefile.id"
)
# 2) Tell CMake to run the script before any build
add_dependencies(my_app run_gen_script)
# 3) This ensures that CMake re-runs configure step if somefile.id changes
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${ID_FILE}")
# 4) Read the current value from somefile.id
file(READ "${ID_FILE}" _var_from_file)
string(STRIP "${_var_from_file}" _var_from_file)
# 5) Build the executable
add_executable(my_app
foo.c
bar.c # other source files go here
)
# 6) Apply the compile definition only to foo.c
set_source_files_properties(
foo.c
PROPERTIES
COMPILE_DEFINITIONS "VAR=${_var_from_file}"
)
# ---------------------------------------------------------------------------
🔍 How It Works
-
add_custom_target(run_gen_script ...)
- Runs your
gen_id.sh script before every build.
- Uses
CMAKE_COMMAND -E env to ensure correct environment variables and shell behavior.
-
add_dependencies(my_app run_gen_script)
- Ensures
run_gen_script runs before my_app builds.
- Ninja/Make knows to execute this first.
-
set_property(...CMAKE_CONFIGURE_DEPENDS...)
- Makes CMake reconfigure if
somefile.id has changed since last configure.
-
Re-reading somefile.id during configuration
- If the file was updated by
gen_id.sh, its new contents are picked up.
- The new value is used in
-DVAR=... for foo.c.
-
Only foo.c gets the define
- Using
set_source_files_properties() ensures only foo.c sees -DVAR=....
🧪 Example: gen_id.sh
For testing, you can create a simple gen_id.sh like this:
#!/bin/bash
echo $(( RANDOM % 1000 )) > somefile.id
Make sure it's executable:
chmod +x gen_id.sh
📝 Usage
cmake --build .
Now:
gen_id.sh runs first
- If
somefile.id changes → CMake reconfigures
- New
-DVAR=... is applied to foo.c
- Only
foo.c gets rebuilt if needed
Let me know if you want this to work even when somefile.id doesn't exist initially or needs to be generated on first run!