I found a way to do this. Not too sure how robust or portable it is though. This solution assumes the shell is bash. In the makefile I have
GIT_DIFF := $(shell printf '%q
' "$$(git diff | awk '{ gsub(""","\"",$$$$1) ; print $$$$1 }' ORS='\n')" )
CXXFLAGS += -DGIT_DIFF="$(GIT_DIFF)"
and then in a header file I have
// Convert macro to a string constant
#define STRINGIFY1(x) #x
#define STRINGIFY(x) STRINGIFY1(x)
constexpr auto git_diff = STRINGIFY(GIT_DIFF)
(this is a C++11 project).
Unpacking that command a bit:
The string that's passed to the C++ code is full of escape sequences, so is not very readable. It can be converted back to something more readable by reversing the awk
substition and using echo -e
to evaluate the escaped characters (for some reason this needs to be done twice). So if the string is saved into a text file, say mygitdiff
, then
echo -e $(echo -e "$(cat mygitdiff | awk '{ gsub("\"", """,$$1) ; print $$1 }' IRS='\n')")
should make it something readable.
This method is awkward, and the string that's passed to the C++ isn't very readable, so if anyone has a better solution, or suggestions for improvements, that would be very welcome!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…