You can write a script that does something like this:
for each $pkg in dpkg-query -W -f '${status} ${package}\n' | sed -n 's/^install ok installed //p'
:
- run apt-get source $pkg
- run apt-get build-dep $pkg
- cd $pkg-version/
- run DEB_CPPFLAGS_SET="-I/foo/bar/baz" DEB_CFLAGS_SET="-g -O3" DEB_LDFLAGS_SET="-L/fruzzel/frazzel/" dpkg-buildpackage
- install package with dpkg -i deb-file
- cd ..
This will go through all of your installed packages and generate .deb files for each of them. Probably there are some edge cases etc. that will have to be handled. You could also leave out packages that are not built from C code etc.
Info taken from these questions:
https://unix.stackexchange.com/questions/184812/how-to-update-all-debian-packages-from-source-code
How to override dpkg-buildflags CFLAGS?