链接和使用头文件有什么区别? [英] What is the difference between linking and using a header file?

查看:112
本文介绍了链接和使用头文件有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,链接两个文件有什么区别

For example, what is the difference between linking two files

gcc -c func.c 
gcc -c main.c 
gcc func.o main.o -o main 

并使用头文件

#include func.h

int main{
....
.. 
}

如果他们似乎完成了同一件事? / p>

if they seem to accomplish the same thing?

推荐答案

他们不完成同一件事。他们完成同一件事的互补部分。通常,您必须同时做这两种事情:仅做一项或另一项是完全不够的。

They don't "accomplish the same thing". They accomplish complementary parts of the same thing. Typically you have to do both: doing just one, or just the other, is totally insufficient.

在这里有一个不完美的类比:假设您想在房子上加个东西。在项目开始时,您与建筑商签订了合同,指定了添加的大小和完成的名称。在项目结束时,您在支票上签名,以向建造者付款。签订合同和签支票有什么区别?如果它们都做同样的事情,就是为什么要同时做这两个事情,即让您获得新的加成?

Here's an imperfect analogy: Suppose you want an addition on your house. At the start of the project, you sign your name on a contract with the builder, specifying the size and finish of the addition. At the end of the project, you sign your name on a check to pay the builder for his work. What's the difference between signing the contract and signing the check? Why do you have to do both, if they both do the same thing, namely getting you your new addition?

包含标头就像(签订合同)一样。当您说 #include< math.h> 时,您的意思是嘿,编译器,有一些数学函数。例如 sqrt() ,它接受 double 并返回 double 。因此,如果我写 int x = sqrt(144),请确保您执行了从 int double ,然后将数字传递给 sqrt ,并确保您将 double 转换为 int ,然后将结果分配给 x

Including a header is (sort of) like signing a contract. When you say #include <math.h>, you're saying "Hey, compiler, there are some math functions. Like sqrt(), which accepts a double and returns a double. So if I write int x = sqrt(144), make sure you do a conversion from int to double before passing the number to sqrt, and make sure you do a conversion from double back to int before assigning the result to x."

针对图书馆就像在付账单一样。 (实际上,如果我说实话,那几乎不像是付账单,而是要忍受。)在命令行末尾放置 -lm 时,您会的意思是,嘿,编译器,我们同意的那些数学函数,详细信息在合同中指定的< math.h> 一直在打电话,现在我付款了,这实际上是这些功能 的位置。

Linking against a library is (sort of) like paying your bill. (Actually, if I'm honest, it's almost nothing like paying a bill, but bear with me.) When you put -lm at the end of the command line, you're saying "Hey, compiler, those math functions we agreed on, the ones whose details are specified in the contract called <math.h>, the ones I've been calling, now I'm paying up, here's where those functions actually are."

这篇关于链接和使用头文件有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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