C/C++:头文件中的静态函数,是什么意思? [英] C/C++: Static function in header file, what does it mean?

查看:23
本文介绍了C/C++:头文件中的静态函数,是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在源文件中声明静态函数意味着什么.我正在阅读一些代码,发现头文件中的静态函数可以在其他文件中调用.

I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.

推荐答案

函数是否定义在头文件中?这样在函数中直接给出实际的代码,像这样:

Is the function defined in the header file? So that the actual code is given directly in the function, like this:

static int addTwo(int x)
{
  return x + 2;
}

那么这只是为许多不同的 C 文件提供有用函数的一种方式.每个包含头文件的 C 文件都将获得自己可以调用的定义.这当然会浪费内存,并且(在我看来)是一件非常丑陋的事情,因为在标头中包含可执行代码通常不是一个好主意.

Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.

请记住,#include:ing 头文件基本上只是将头文件的内容(以及它包含的任何其他头文件)粘贴到编译器看到的 C 文件中.编译器永远不知道一个特定的函数定义来自头文件.

Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.

更新:在许多情况下,做上述类似的事情实际上是个好主意,我意识到我的回答听起来非常黑白分明,这有点过于简单化了.例如,建模(或仅使用)内在函数的代码可以像上面那样表达,并且使用显式 inline 关键字 even:

UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:

static inline int addTwo(int *x)
{
  __add_two_superquickly(x);
}

这里,__add_two_superquickly() 函数是一个虚构的内在函数,因为我们希望整个函数基本上编译为一条指令,所以我们真的希望它被内联.尽管如此,以上还是比使用宏更干净.

Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.

与仅直接使用内在函数相比的优势当然是将其包装在另一层抽象中,通过提供替代实现并根据哪个编译器选择正确的实现,可以在缺少特定内在函数的编译器上构建代码正在使用中.

The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.

这篇关于C/C++:头文件中的静态函数,是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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