5

I'm working with libsystemd-dev (a C library) in my C++ application.

I get a gcc/clang pedantic warning

compound literals are a C99-specific feature

with this code:

#include <systemd/sd-bus.h>

void foo()
{
  sd_bus_error err = SD_BUS_ERROR_NULL;  // compound literals are a C99-specific feature
  ...
}

Looking at the <systemd/sd-bus.h> header file, I see:

typedef struct {
        const char *name;
        const char *message;
        int _need_free;
} sd_bus_error;

#define SD_BUS_ERROR_MAKE_CONST(name, message) ((const sd_bus_error) {(name), (message), 0})
#define SD_BUS_ERROR_NULL SD_BUS_ERROR_MAKE_CONST(NULL, NULL)

This means I can solve the warning with:

#include <systemd/sd-bus.h>

void foo()
{
  sd_bus_error err = {nullptr, nullptr, 0};
  ...
}

But is that a good idea? If the library changes, my code would need to change too so I feel that it's volatile. Is there really any problem with this warning? Is there a better way to get around it?

There is always the method of just using compiler flags to disable the warning, but I was wondering if there could be an encouraged method in-code to address this.

Stewart
  • 4,356
  • 2
  • 27
  • 59
  • Enabling the extension isn't the end of the world. – StoryTeller - Unslander Monica Jun 17 '19 at 07:22
  • 4
    The purist that I am, I would have a 'thunk' file that wrapped up these C constructs in a gobal C++ function. I would only enable to extensions for that thunk file and call the C++ functions whenever I needed the behavior. – Omnifarious Jun 17 '19 at 07:30
  • A C library may not be rewritten with C++ in mind. After all, it is perfectly valid C99. So you may well encounter some inelegance when you try to use it from C++. But either way ... – L. F. Jun 17 '19 at 10:40
  • Possible duplicate of [How to disable warnings for particular include files?](https://stackoverflow.com/questions/6321839/how-to-disable-warnings-for-particular-include-files) – L. F. Jun 17 '19 at 10:42
  • Disabling specific warnings is obviously an easy solution. I was wonder if there was something that I was missing that I could do in the code to address the issue directly. It seems the answer is 'no'. Thanks! – Stewart Jun 17 '19 at 11:02

1 Answers1

4

Omnifarious already hinted at one approach - use extensions inside a wrapper function. The slightly more robust method is to use an extern "C" wrapper function, in its own Translation Unit. Compile that whole Translation Unit as C11, without extensions.

This is generally more robust. Mixing code at source level requires advanced compiler support, whereas linking C and C++ is fairly straightforward.

MSalters
  • 173,980
  • 10
  • 155
  • 350