Where to add a CFLAG, such as -std=gnu99, into an autotools project

fadedbee picture fadedbee · Jul 25, 2012 · Viewed 28.3k times · Source

I have a simple Autotools C project (not C++).

CFLAGs (by inspection) seem to be -g -O2.

I want all of the generated make files to also have -std=gnu99 appended to the CFLAGs, because I use for (int i = 0; i < MAX; i++) and similar.

I can obviously hack the Makefile, but this gets overwritten on ./configure.

Where is the correct place to add (or change) CFLAGs which are required by the code (as opposed to those CFLAGs which the user might want to change)?

(Note this is partial duplicate of Where to add a CFLAG, such as -std=gnu99, into an (Eclipse CDT) autotools project as I was getting Eclipse-specific answers which I didn't want.)


@DevSolar's answer has not helped yet. A configure.ac file (below) generates the configure script (also below).

configure.ac:

dnl Process this file with autoconf to produce a configure script.

CFLAGS="$CFLAGS -std=gnu99"
AC_PREREQ(2.59)
AC_INIT(tuntest, 1.0)


AC_CANONICAL_SYSTEM
AM_INIT_AUTOMAKE()

AC_PROG_CC

AC_CONFIG_FILES(Makefile src/Makefile)
AC_OUTPUT

$ grep CFLAGS configure

CFLAGS
CFLAGS
To assign environment variables (e.g., CC, CFLAGS...), specify them as
  CFLAGS      C compiler flags
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_test_CFLAGS=${CFLAGS+set}
ac_save_CFLAGS=$CFLAGS
   CFLAGS="-g"
  CFLAGS=""
     CFLAGS="-g"
if test "$ac_test_CFLAGS" = set; then
  CFLAGS=$ac_save_CFLAGS
    CFLAGS="-g -O2"
    CFLAGS="-g"
    CFLAGS="-O2"
    CFLAGS=
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'

Answer

hroptatyr picture hroptatyr · Jul 25, 2012

autoconf has a macro for this:

Just put:

AC_PROG_CC_STDC

after your AC_PROG_CC and everything will be right.

Especially when you use other compilers that do not have -std=gnu99 but operate in C99 mode by default (or have a different option hpcc's -AC99 springs to mind).

I would NOT use CFLAGS for that kind of thing.

From the docs:

-- Macro: AC_PROG_CC_STDC
If the C compiler cannot compile ISO Standard C (currently C99),
try to add an option to output variable `CC' to make it work.  If
the compiler does not support C99, fall back to supporting ANSI
C89 (ISO C90).

After calling this macro you can check whether the C compiler has
been set to accept Standard C; if not, the shell variable
`ac_cv_prog_cc_stdc' is set to `no'.