C和c++中的内联函数;沉默编译器警告
Inline functions in C and C++; silencing compiler warning
我已经嵌入了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...
在它自己的头文件和它自己的头保护:
#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
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- C和c++中的内联函数;沉默编译器警告
- 如何使用未使用的宏在CONSTEXPR函数中沉默警告