user_CFLAGS=$CFLAGS
AC_PROG_CC
if test "x$user_CFLAGS" = x; then
# If the user didn't specify CFLAGS, then CFLAGS contains
# a subset of -g -O2 selected by AC_PROG_CC. This is not
# a user setting, and we want to be able to override this
# locally in our rules, so put these flags in a separate
# variable and empty CFLAGS.
AC_SUBST([DEFAULTFLAGS], [$CFLAGS])
CFLAGS=
fi
and in Makefile.am use
foo_CFLAGS = $(DEFAULTFLAGS)
and
libfoo_a_CFLAGS = $(DEFAULTFLAGS) $(O3)
as appropriate.
($(O3) being the Makefile variable that contains -O3 if the compiler
support it).