不同文件中的函数头和实现 C
如何拥有一个函数的头文件以及该函数在不同文件中的实现?另外,如何将 main 放在另一个文件中并调用此函数? 好处是这样这个功能就可以成为一个独立的组件,可以重复使用,对吗?
How do you have a header file for a function and the implementation of that function in different files? Also, how do you have main in yet another file and call this function?
The advantage is so that this function will then be an independent component which can be reused, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好用一个例子来说明这一点。
假设我们想要一个函数来计算整数的立方。
您将在
cube.c
中获得定义(实现),然后我们将函数声明放在另一个文件中。按照惯例,这是在 头文件、
cube.h
中完成的在这种情况下。现在,我们可以使用
#include
指令(它是 C 预处理器的一部分)从其他地方(例如driver.c
)调用该函数。最后,您需要将每个源文件编译为目标文件,然后链接它们以获得可执行文件。
例如,使用gcc
This is best illustrated by an example.
Say we want a function to find the cube of an integer.
You would have the definition (implementation) in, say,
cube.c
Then we'll put the function declaration in another file. By convention, this is done in a header file,
cube.h
in this case.We can now call the function from somewhere else,
driver.c
for instance, by using the#include
directive (which is part of the C preprocessor) .Finally, you'll need to compile each of your source files into an object file, and then link those to obtain an executable.
Using gcc, for instance
实际上,只要不引用特定对象(实际上它不会编译该对象),您就可以在头文件中实现任何函数以获得更好的性能(例如,在实现库时)。
顺便说一句,即使采用这种方式,您也有单独的接口和实现;)
当然,您将在头文件中包含 gurad 以避免“多重定义”错误。
Actually you can implement any function in header files for better performance(when implementing libraries for example) as long are not referenced to a specific object(actually it won't compile that).
By the way even with that way, you have separate interface and implementation ;)
Of course you will have include gurads in you header files to avoid "multiple definition" errors.
在 C/C++ 中,非内联函数只能定义一次。如果你把函数定义
在头文件中,当多次包含头文件时,您将收到“多重定义”链接错误。
In C/C++, non-inline functions should be defined only once. If you put function defination
in header files, you will get "multiple defination" link error when the header file is included more than once.