Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate const error with C++ wrapping C code

Tags:

c++

c

c++11

g++4.8

I've got some C code that is included and used from a C++ application, the important parts here:

C code

ifdef __cplusplus
extern "C" {
endif

...
typedef void* problem_type;

...
int problematic_fn_proto( const problem_type const arg );

ifdef __cplusplus
}
endif

Unfortunately, this will not compile due to a duplicate 'const' error. It's the typedef that causes the problem. If I just change the prototype for the function to:

int problematic_fn_proto( const void* const arg );

No more problems. Unfortunately, I cannot remove the typedef. Is there a solution here? I can make other changes to the C portion, but the typedef and it's use as the argument to the function must remain.

like image 880
davepmiller Avatar asked Mar 14 '23 10:03

davepmiller


1 Answers

The reason you're getting this is that now problem_type is a type in it's own right, but the only place where double const (const directly before and after a type has the same meaning) makes sense is if you're using pointers. There's a few options if you still want to use typedef

First is to not include pointer in the typedef:

typedef void problem_type;
int problem_fn_proto( const problem_type* const arg);

The second is to include the const specifier in the typedef:

typedef void const* cproblem_type;
typedef void* problem_type; // non-const variant not used here
int problem_fn_proto(cproblem_type const arg);

In the last solution the cproblem_type is a pointer to constant data, using cproblem_type const means a constant of that (that is a constant pointer to constant data).

Third solution is to notice that constness of an argument doesn't mean much. If the function happens to modify the argument it's not seen from the caller:

typedef void const* cproblem_type;
int problem_fn_proto(cproblem_type arg);
like image 89
skyking Avatar answered Mar 21 '23 02:03

skyking