[petsc-dev] Request for comments: allow C99 internally

Jed Brown jed at jedbrown.org
Fri Mar 6 23:48:32 CST 2020


I have a question for petsc-dev: Do you know anyone who needs to build
PETSc with a compiler that doesn't support variadic macros and for-loop
declarations?  (Both of these are in C99 and C++11, and supported by all
tested configurations including compilers that don't fully implement
these standards.)  Both MPICH and Open MPI use variable-length arrays
and for-loop declarations, so you'd be hard-pressed building a modern
stack with such a compiler.  I'm not proposing that we put these macros
unguarded into the public headers, so a user of PETSc could still build
with -std=c89 and the like.


## Background

There is a common pattern in PETSc where we write

  PetscInt some,several,variables;

  // code
#if defined(PETSC_HAVE_MAGIC)
  function(several,&variables);
#endif
  use(some,variables);


Of course this gives unused variable warnings, so we tear our code apart like

  PetscInt some,variables;
#if defined(PETSC_HAVE_MAGIC)
  PetscInt several;
#endif

  // code
#if defined(PETSC_HAVE_MAGIC)
  function(several,&variables);
#endif
  use(some,variables);


but the bigger problem is that we need different configurations just to
check syntax of our compiled out blocks.  I propose allowing variadic
macros (a C99 and C++11 feature) to allow code like

  PetscInt some,several,variables;

  // code
  if (PetscDefined(HAVE_MAGIC)) {
    function(several,&variables);
  }
  use(some,variables);


This approach could also be used to avoid needing separate macros for
every SETERRQ1-SETERRQ9, etc.  I have an example implementation in this
MR, and it passes the full pipeline (after relaxing the -std=c89
-pedantic build).

https://gitlab.com/petsc/petsc/-/merge_requests/157/diffs


We could also consider allowing for-loop declarations, which I believe
leads to tighter and more understandable code because the reader doesn't
have to wonder whether the variable is used after the loop.

  for (PetscInt i=0; i<n; i++) { ... }


Note that we cannot use variable-length arrays (VLA) because they are
not in the intersection of C and C++.


More information about the petsc-dev mailing list