lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> 
> On Monday, February 13, 2023 at 07:17:42 AM CST, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote: 
> 
> > Lua is designed with ISO C in mind as its host. Any bit specific for
> > Windows/Unix should be explicitly turned on by some macro. It should
> > compile and run in *any* hosted implementation of C that satisfies
> > either the C 89 standard or the C 99 standard. (C 99 out of the box,
> > C 89 with the macro LUA_USE_C89 defined.)
> 
> Which raises the question: is there a guide or written standard for
> maximally portable code and/or "clean C" that Lua's written in? Beyond
> C 99 and C 89, I mean. I'm sure there are some things in C *can* do
> that you shouldn't because, for example, some hosted environment's
> memory model will throw a fit. (Just like Java's "write once run
> anywhere" was wildly optimistic.)

Over the years, I think our team accumulated a good expertise on writing
"clean C", but we never wrote anything about it. But we have some
rules of thumb:

- Get a copy of the ISO standard and be familiar with it.

- Avoid undefined behaviors, even when they don't make sense to you.
When that is unfeasible, make explicit your assumptions. (For instance,
that the machine uses two-complement and that a cast from an unsigned int
to a signed int will do nothing to the bits.)

- Avoid features that behave differently in C++. (Well, that's the
definition of Clean C...)  Some compilers fail to correctly implement
these distinctions. When possible, test your code as if it was C++.
When using gcc, use the warning '-Wc++-compat'.

- Always use as many warnings as feasible (and fix all warnings).
When using gcc, use the option '-std=c99' (or whatever the standard
you are assuming).

- Avoid 'char' without an explcit 'signed'/'unsigned' whenever
possible. When accessing '*s' (where s is 'char*'), always cast it
to a 'signed' or 'unsigned' char.

- Avoid implicit "multi-step" type conversions (e.g., float -> unsigned char).


-- Roberto