C和c++中的内联函数;沉默编译器警告

Inline functions in C and C++; silencing compiler warning

本文关键字:函数 沉默 编译器 警告 c++      更新时间:2023-10-16

我已经嵌入了C代码,我正在用c++框架进行单元测试。C和c++处理内联函数的方式不同,所以当我想创建在两个源文件中使用的内联函数时,我这样做:

头文件:

#ifdef __cplusplus
# define INLINE inline
#else
# ifndef INLINE
#  define INLINE extern inline
# endif
#endif
INLINE Uint8 my_inline_function( Uint8 stuff )
{
    return stuff;  // not really, but it's not germane to the example
}

恰好在两个。c文件中的一个中:

#define INLINE

现在C和c++编译器都满足了,但是当我构建时,我得到了这个警告:

In file included from ../MyFile.c:28:0,
             from utest_MyFile.cpp:10:
../MyFile.h:53:0: warning: "INLINE" redefined
../MyFile.c:26:0: note: this is the location of the previous definition

是否有一种方法可以将此警告静音?

使用#ifndef

#ifndef INLINE
# ifdef __cplusplus
#  define INLINE inline
# else
#  define INLINE extern inline
# endif
#endif

您可能在同一个翻译单元中多次包含该定义。你可以添加include守卫:

#ifndef INLINE_DEFINED
#define INLINE_DEFINED
#ifdef __cplusplus
# define INLINE inline
#else
# ifndef INLINE
#  define INLINE extern inline
# endif
#endif
//...
#endif

或取消定义指令:

#undef INLINE
#ifdef __cplusplus
# define INLINE inline
#else
# ifndef INLINE
#  define INLINE extern inline
# endif
#endif

更困难的方法是将警告静音:

#pragma warning( disable : /*warning number*/ )

不确定这是不是跨平台的

首先,正如Charles在他的评论中所说,你不应该这样做,C和c++是本质上不同的语言。特别是它们对于inline函数的规则是不同的。这会使你痛苦的。

那么,你就有了另一个设计缺陷。这是显而易见的,因为您正在尝试重新定义一个宏。INLINE有两种不同的情况所以它们代表两种不同的东西。我认为下面的模型更简单和直接:

  • 使用inline作为头文件。没有宏观或类似的东西,没有extern
  • 在一个C或c++文件中为相同的函数
  • 放置一个"实例化"

你应该决定你的实例化是C还是c++,不要在这里玩游戏。在C语言中,这样的实例化是

extern inline Uint8 my_inline_function( Uint8 stuff );

(C不调用实例化但是我们用c++的术语)

在c++中应该是

Uint8 my_inline_function( Uint8 stuff );

就是这样,不需要魔法:

  • 所有包含头文件的编译单元都有一个定义可用
  • 适用于所有仍然需要链接器符号的情况实例化将被使用

编辑:

看到你的评论(这并不能完全说服我),我认为你会更好的只有一个宏实例化在头文件

#ifdef __cplusplus
# define INSTANT
#else
# define INSTANT extern inline
#endif

,然后在一个。c或。c或任何你需要说服编译器

INSTANT Uint8 my_inline_function( Uint8 stuff );

你应该有#define INLINE...在它自己的头文件和它自己的头保护:

(inline.h)
#ifndef INLINE_DEFINED
#ifdef __cplusplus
# define INLINE inline
#else
# ifndef INLINE
#  define INLINE extern inline
# endif
#endif
#endif

你应该把#include "inline.h"放在任何需要它的文件的顶部。

我很欣赏避免C和c++结合的建议,但是我们觉得更严格的类型检查和更易于使用的单元测试框架的好处超过了这些问题。考虑到这一点,我发现最干净的方法是在。c文件中替换

#define INLINE

#ifndef __cplusplus
# define INLINE
#endif

我怀疑这就是导致问题的原因

#ifdef __cplusplus
# define INLINE inline

尝试将其更改为

#ifdef __cplusplus
# ifndef INLINE
# define INLINE inline
#endif