[systemd-devel] string constants vs. #defines [was: Re: [PATCH v4] udev hwdb: Support shipping pre-compiled database in system images]

Lennart Poettering lennart at poettering.net
Mon Oct 27 08:20:29 PDT 2014


On Sun, 26.10.14 07:51, Martin Pitt (martin.pitt at ubuntu.com) wrote:

> > > +static const char hwdb_bin_paths[] =
> > > +    "/etc/udev/hwdb.bin\0"
> > > +    UDEVLIBEXECDIR "/hwdb.bin\0";
> > Actually we don't need to define a variable for this, a #define would be enough.
> 
> Are #defines actually preferred in systemd's code style/conventions?
> Personally I prefer "proper" constants, as they are more type safe and
> less magic, and presumably string constants will end up in the same
> place in the ELF anyway? Using #defines potentially duplicates the
> strings too, although I suspect gcc to be clever enough to
> de-duplicate identical string constants in the source. Is there any
> downside to using static constants?

Well, there's quite a difference between string macros and string
constants. In C string macros are usually preferable, since they allow
compilers to arrange things pretty freely, as they do not imply
the actual allocation of a variable in the ELF result for this.

Moreover, string macros have the benefit that you can use them to put
together strings at build time, the way you do it above even. 

Currently, in systemd we try to be conservative:

a) Paths that are not really configurable aren't really made
   configurable, and hence are hardcoded as literal strings (such as
   the "/etc/udev" above...) Given that systemd is pretty much at the
   core of the OS very little of systemd is relocatable, which in turn
   means that most of its own paths are actually not configurable. In
   fact we should probably refuse building if people try to build
   systemd with prefix=/waldo...

b) For configurable and non-obvious strings we use string macros

b) Complex strings, for example NULSTR-style things, that "feel" more
   like an array than a real string are placed in string constants.

That alls said, the lines are blurry and we don't follow these rules
strictly so far...

Hope that makes sense?

Lennart

-- 
Lennart Poettering, Red Hat


More information about the systemd-devel mailing list