I have a utility library of C99 code used by C++11 application code. A few inline functions are declared in the C99 style with code explicitly generated in the translation unit like:
// buffer.h
inline bool has_remaining(void* obj) {
...
}
// buffer.c
extern inline bool has_remaining(void * obj);
However, when I try to use has_remaining
in the C++ application, I get errors about multiple definitions at link time. It seems that g++ is instantiating the inline code that already exists in the library, despite the extern "C"
header guards specifier.
Is there a way to coerce g++ into working with this type of definition?
It looks like if I #ifdef __cplusplus
an extern definition with the gnu_inline
attribute, the right thing will happen, but surely there is a more portable way to keep modern C headers compatible with modern C++?
-- Edit: Working Example --
buffer.h:
#ifndef BUFF_H
#define BUFF_H
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
inline bool has_remaining(void const* const obj) {
return (obj != NULL);
}
#ifdef __cplusplus
}
#endif
#endif /* BUFF_H */
buffer.c:
#include "buffer.h"
extern inline bool has_remaining(void const* const obj);
app.cpp:
#include <stdlib.h>
#include <stdio.h>
#include "buffer.h"
int main(int argc, char** argv) {
char const* str = "okay";
printf(str);
has_remaining(str);
return (0);
}
compile:
$ gcc -std=gnu99 -o buffer.o -c buffer.c
$ g++ -std=gnu++11 -o app.o -c app.cpp
$ g++ -Wl,--subsystem,console -o app.exe app.o buffer.o
buffer.o:buffer.c:(.text+0x0): multiple definition of `has_remaining'
app.o:app.cpp:(.text$has_remaining[_has_remaining]+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
--Edit 2--
The __gnu_inline__
attribute does indeed fix the problem of multiple definitions. I'd still like to see a (more) portable approach or some conclusive reasoning why one doesn't exist.
#if defined(__cplusplus) && defined(NOTBROKEN)
#define EXTERN_INLINE extern inline __attribute__((__gnu_inline__))
#else
#define EXTERN_INLINE inline
#endif
EXTERN_INLINE bool has_remaining(void const* const obj) {
return (obj != NULL);
}