C99中如何定义内联内部和外部复制的函数
我的库包含一个可在内部和外部使用的函数。该函数非常小,我希望编译器在调用内部函数时尝试内联函数。由于函数使用不完整类型的信息,外部调用无法内联。因此,我的模块还应该始终包含具有外部链接的函数的副本。
我想我找到了以下解决方案,但希望得到您的建议:
/* stack.h */
struct stack;
extern bool stack_isempty(struct stack *s);
/* stack.c */
#include "stack.h"
struct stack { [...]; int size; };
inline bool stack_isempty(struct stack *s) { return s->size == 0; }
通常我以相反的方式使用内联,或者只在头文件中放置一个静态内联函数。但正如所解释的,这在这里是不可能的。
这种方法能达到预期的结果吗?有人看到这种方法有什么缺点吗(它是便携式 C99)吗?
My library contains a function that is used both internal and external. The function is so small that I want the compiler to try to inline function when called internal. Because the function uses information of an incomplete type external calls cannot be inlined. So my module should also always contain a copy of the function with external linkage.
I think I found the following solution, but would like your advice:
/* stack.h */
struct stack;
extern bool stack_isempty(struct stack *s);
/* stack.c */
#include "stack.h"
struct stack { [...]; int size; };
inline bool stack_isempty(struct stack *s) { return s->size == 0; }
Usually I use inline the other way around or only put a static inline
function in the header file. But as explained this is not possible here.
Does this approach give the desired results? Does anyone see any disadvantages to this approach (Is it portable C99)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 C99 规则,这看起来完全没问题。由于
stack.c
是使用函数的extern
和inline
声明进行编译的,因此它将使用外部链接进行定义,也可以进行内联在该文件中。其他文件将只有声明,因此将链接到具有外部链接的版本。
请注意,该函数不允许定义任何具有静态存储持续时间的可修改对象,也不允许引用任何非
extern
的函数或全局变量。That looks perfectly fine under the C99 rules. Because
stack.c
is compiled with both anextern
andinline
declaration of the function, it will be defined with external linkage and can also be inlined within that file.Other files will have only the declaration, and so will link to the version with external linkage.
Note that the function isn't allowed to define any modifiable objects with static storage duration, or reference any functions or global variables that aren't
extern
.