在.c文件C99内联函数 [英] C99 inline function in .c file

查看:75
本文介绍了在.c文件C99内联函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义我的.C(无头声明)函数如下:

I defined my function in .c (without header declaration) as here:

inline int func(int i) {
 return i+1;
}

然后在同一个文件下面我用它:

Then in the same file below I use it:

...
i = func(i);

和链接时我得到未定义引用'功能'。为什么呢?

And during the linking I got "undefined reference to 'func'". Why?

推荐答案

在C99的在线模型比大多数人有点不同的思考,特别是不同于一惯以C ++

The inline model in C99 is a bit different than most people think, and in particular different from the one used by C++

在线只是一个提示,这样编译器不会抱怨双重定义的符号。它并不能保证一个内联函数,实际上也就是产生一个符号,如果需要的话。要强制一个符号的产生,你不得不后添加一个排序实例的的的在线定义:

inline is only a hint such that the compiler doesn't complain about doubly defined symbols. It doesn't guarantee that a function is inlined, nor actually that a symbol is generated, if it is needed. To force the generation of a symbol you'd have to add a sort of instantiation after the inline definition:

int func(int i);

通常你必须在在线在头文件的定义,那就是再包括在几个.c文件(编译单元)。而你只需要在编译单元只有一个上面一行。你可能只看到你有,因为你不使用优化编译器运行的问题。

Usually you'd have the inline definition in a header file, that is then included in several .c files (compilation units). And you'd only have the above line in exactly one of the compilation units. You probably only see the problem that you have because you are not using optimization for your compiler run.

因此​​,具有在线在.c文件的您的使用情况并没有多大意义,更好地只是使用静态注意到,即使额外的在线不买你的了。

So, your use case of having the inline in the .c file doesn't make much sense, better just use static for that, even an additional inline doesn't buy you much.

这篇关于在.c文件C99内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆