如何在 C99 中正确内联和使用内联函数,纠正链接故障?
在以下简化的 example.c
文件上执行 cc -std=c99 example.c
:
inline void a()
{
}
int main()
{
a();
return 0;
}
让我:
在函数“main”中:
example.c:(.text+0x7): 对“a”的未定义引用
collect2:ld返回1退出状态
据我了解,这与 C99 标准的要求有关,即要求为在无法内联主体的情况下使用的每个内联非静态函数再定义一个定义?如果是这样,我猜我可以用 static inline
来代替,但我不希望这个问题稍后困扰我,那么这里最好的做法是什么?显然,我想坚持使用 C99 并且我想内联一些函数。 (是的,我知道编译器通常知道要内联什么而不被告知,但我有我的理由)
Doing cc -std=c99 example.c
on the following simplified example.c
file:
inline void a()
{
}
int main()
{
a();
return 0;
}
gets me:
In function `main':
example.c:(.text+0x7): undefined reference to 'a'
collect2: ld returned 1 exit status
As I understand this has to do with the requirement of C99 standard to demand exactly one more definition for each inline non-static function that is used in cases where the body cannot be inlined? If that is so, I am guessing I could do with static inline
instead, but I don't want this to bite me later, so what would be the best course of action here? Obviously, I want to stick to C99 and I want to inline some functions. (Yes, I am aware the compiler usually knows what to inline without being told so, but I have my reasons)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用 -O2 左右进行编译时,可能不会出现该错误。
内联函数定义应位于头文件中,
extern inline
声明应位于one编译单元中。顺便说一句,声明没有
void
的a
不是原型。Probably you wouldn't have that error when you compile with -O2 or so.
Inline function definitions should go in header files and an
extern inline
declaration should go in one compilation unit. DoBTW, declaring
a
withoutvoid
is not a prototype.没有函数原型,仅此而已,因此函数签名被推断出来,并且推断错误。添加“void a();”到文件顶部,一切就完成了。
There's no function prototype, that's all, so the function signature is inferred, and inferred wrong. Add "void a();" to the top of the file, and you're all set.