C头中的函数? [英] Functions in C Headers?

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

问题描述

我听说你将函数原型放在头文件中,然后把函数定义放在一个.c文件中。但是,这是什么.c文件。例如,如果你要包含一个文件foo.h,你会调用前面提到的.c文件foo.c,将函数定义放入它中,并将它放在与foo.h相同的位置,并且当你试图包含foo.h时,这个函数是否会从c文件中继承下来,并且这个函数是否可以使用?

解决方案

不,只要将 .c .h 并将其包含在您的代码中,不会奇迹般地携带在功能的定义上也是如此。

您需要将 foo.c 分别编译到一个目标文件中(在Linux的情况下,它是一个 .o 文件)。例如使用命令 -

  gcc -c foo.c -o foo.o 

现在这个 foo.o 需要链接你的实际程序。这可以通过在编译时简单地传递目标文件来完成,如

  gcc test.c foo.o -o test.out 

如果您不链接 foo.o 在你的程序中,你的链接程序将无法找到其中定义的函数的实现,并会抛出链接器错误 -


对函数 foo_function 的未定义引用。



I've heard that you put function prototypes in header files and then put the function definitions in a .c file. However, what is this .c file. For example, if you were to include a file "foo.h", would you call the aforementioned .c file "foo.c", put the function definition in it, put it in the same place as the foo.h, and when you try to include foo.h, will the function carry over from the c file and will the function be ready to use?

解决方案

No, just putting the .c with the .h and including it in your code doesn't magically carry over the definition of the functions too.

You need to compile the foo.c separately into an object file (in case of Linux, it is a .o file). For example using the command -

gcc -c foo.c -o foo.o

Now this foo.o needs to be linked to your actual program. This can be done by simply passing the object file while compiling as

gcc test.c foo.o -o test.out

If you do not link the foo.o with your program, your linker won't be able to find the implementations for the functions defined in it and will throw a linker error as -

Undefined reference to function foo_function.

这篇关于C头中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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