其他分享
首页 > 其他分享> > C99和C的内联函数的兼容定义

C99和C的内联函数的兼容定义

作者:互联网

我有一个C 11应用程序代码使用的C99代码实用程序库.一些内联函数以C99样式声明,并在翻译单元中显式生成了如下代码:

// buffer.h
inline bool has_remaining(void* obj) {
...
}

// buffer.c
extern inline bool has_remaining(void * obj);

但是,当我尝试在C应用程序中使用has_remaining时,在链接时会收到有关多个定义的错误.似乎g正在实例化库中已经存在的内联代码,尽管存在外部的“ C”头保护了指定符.

有没有一种方法可以强制使用这种类型的定义?

看起来如果我#ifdef __cplusplus具有gnu_inline属性的extern定义,将会发生正确的事情,但是肯定有一种更简便的方法来保持现代C标头与现代C兼容?

-编辑:工作示例-

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);
}

编译:

$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

-编辑2–
__gnu_inline__属性确实解决了多个定义的问题.我仍然希望看到一种(更多)可移植的方法或某些结论性理由,说明为什么不存在这种方法.

#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);
}

解决方法:

据报道,这是gcc:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56066
从这里开始讨论后:
http://gcc.gnu.org/ml/gcc-help/2013-01/msg00152.html

在linux上,gcc为内联函数发出弱符号,而为外部内联函数发出强符号.在链接时,弱者将被丢弃,而强者则被丢弃.显然,在Windows上,处理方式有所不同.我对Windows没有任何经验,所以我不知道那里发生了什么.

标签:c-3,c,c11,gcc,c99
来源: https://codeday.me/bug/20191011/1889896.html