register keyword in inline function included from C

Viewed 221

I am currently working on a mixed C and C++ project. Lately it happened that external library I have no control over added an inline function containing register keyword to header. For simplicity let's assume header looks like this:

// external_header.h
inline int do_stuff() {
  register int res = 1;
  return res;
}

// some functions declarations without name mangling

And let's assume this is my code (as usless as it is):

// my_code.cpp

#ifdef __cplusplus
extern "C"{
#endif

#include <external_header.h>

#ifdef __cplusplus
}
#endif

int main(inc argc, char** argv) {
  return 0;
}

Compiling my_code.cpp with C++17 switch gives error like this:

error: ISO C++17 does not allow ‘register’ storage class specifier [-Werror=register]

Can there be anything done to work around this error? If so, what is to be done?

2 Answers

Using compiler options, you can disable the -Werror flag for this warning only:

-Werror -Wno-error=register

Or you can disable this warning altogether:

-Wno-register

Or within the code you could use preprocessor macro to remove this keyword. Note that replacing keywords (even unused ones like register) is Undefined Behaviour.

#ifdef __cplusplus
extern "C"{
#endif

#define register

#include <external_header.h>

#undef register

#ifdef __cplusplus
}
#endif

If the C header isn't written in the common subset of C and C++ - and in your case it isn't - then you cannot include it in C++.

If you have no control over the header, then what you can do instead is write a header of your own that is written in valid C++. In order to use the problematic function, you can write a non-inline wrapper function in C where the non C++ header can be included, and delegate to the inline function.

Example:

// external_header.hpp
// ... imagine header guard of your choice here ...
extern "C"{
    int do_stuff_cpp(); // this is valid C++
    // some functions declarations without name mangling
}

// external_header_cpp.c
#include "external_header.h"
int do_stuff_cpp()
{
    return do_stuff();
}
Related