J
Jef Driesen
I have the following problem in a C project (but that also needs to
compile with a C++ compiler). I'm using a virtual function table, that
looks like this in the header file:
typedef struct device_t {
const device_backend_t *backend;
...
} device_t;
typedef struct device_backend_t {
int (*read) (device_t *device, /* parameters */);
int (*write) (device_t *device, /* parameters */);
...
} device_backend_t;
Now when I want to implement a new backend, I write the necessary
functions in the source file:
int mydevice_read (device_t *device, /* parameters */)
{
...
}
int mydevice_write (device_t *device, /* parameters */)
{
...
}
static const device_backend_t mydevice_backend = {
mydevice_read,
mydevice_write,
...
};
So far no problem, but in a number of those functions, I need to have
access to the "mydevice_backend" variable. For instance to check whether
the backend pointer is the correct one. How can I forward declare this
variable properly?
When I add
static const device_backend_t reefnet_sensuspro_device_backend;
to the top of my source file, it works with the gcc compiler, but I'm
not sure this is valid according to the C (or C++) standard. It
certainly doesn't compile with msvc (in C++ mode). It complains about a
redefinition.
How can I make this work? I could move the definition of the
"mydevice_backend" variable to the top of the source file and forward
declare each function inside the structure, but being able to forward
declare the variable itself would be much more elegant.
compile with a C++ compiler). I'm using a virtual function table, that
looks like this in the header file:
typedef struct device_t {
const device_backend_t *backend;
...
} device_t;
typedef struct device_backend_t {
int (*read) (device_t *device, /* parameters */);
int (*write) (device_t *device, /* parameters */);
...
} device_backend_t;
Now when I want to implement a new backend, I write the necessary
functions in the source file:
int mydevice_read (device_t *device, /* parameters */)
{
...
}
int mydevice_write (device_t *device, /* parameters */)
{
...
}
static const device_backend_t mydevice_backend = {
mydevice_read,
mydevice_write,
...
};
So far no problem, but in a number of those functions, I need to have
access to the "mydevice_backend" variable. For instance to check whether
the backend pointer is the correct one. How can I forward declare this
variable properly?
When I add
static const device_backend_t reefnet_sensuspro_device_backend;
to the top of my source file, it works with the gcc compiler, but I'm
not sure this is valid according to the C (or C++) standard. It
certainly doesn't compile with msvc (in C++ mode). It complains about a
redefinition.
How can I make this work? I could move the definition of the
"mydevice_backend" variable to the top of the source file and forward
declare each function inside the structure, but being able to forward
declare the variable itself would be much more elegant.