简体   繁体   中英

Getting around compound literals in C++ to removing the warning

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM