关于C编译过程和库的链接 [英] About C compilation process and the linking of libraries

查看:102
本文介绍了关于C编译过程和库的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C库是否与目标代码 链接,而先与源代码链接,然后才与目标代码链接?我的意思是,看看在卡迪夫计算机科学学院和信息学网站:

Are C libraries linked with object code or first with source code so only later with object code? I mean, look at the image found at Cardiff School of Computer Science & Informatics's website :

"奇怪"是在生成对象代码后将库链接在一起.我的意思是,我们在放入包含内容的同时使用源代码!

It's "strange" that after generating object-code the libraries are being linked. I mean, we use the source code while putting the includes!

所以.. 这实际上如何工作?谢谢!

推荐答案

该图是正确的.

当您 #include 标头时,它实际上会将标头复制到您的文件中.标头是类型,函数声明和常量等的列表,但不包含任何实际代码(尽管有C ++和内联函数).

When you #include a header, it essentially copies that header into your file. A header is a list of types and function declarations and constants, etc., but doesn't contain any actual code (C++ and inline functions notwithstanding).

让我们举个例子: library.h

int foo(int num);

library.c

int foo(int num)
{
    return num * 2;
}

您的代码.c

#include <stdio.h>
#include "library.h"
int main(void)
{
    printf("%d\n", foo(100));
    return 0;
}

当您 #include library.h 时,您将获得 foo()的声明.此时,编译器对foo()或其功能一无所知.尽管如此,编译器仍可以自由地插入对 foo()的调用.链接器在 youcode.c 中看到对 foo()的调用,并在 library.c 中看到了代码,该链接器知道任何对 foo()应该转到该代码.

When you #include library.h, you get the declaration of foo(). The compiler, at this point, knows nothing else about foo() or what it does. The compiler can freely insert calls to foo() despite this. The linker, seeing a call to foo() in youcode.c, and seeing the code in library.c, knows that any calls to foo() should go to that code.

换句话说,编译器告诉链接器要调用的函数,并且链接器(给定所有目标代码)知道该函数的实际位置.

In other words, the compiler tells the linker what function to call, and the linker (given all the object code) knows where that function actually is.

(感谢修饰位.)

这篇关于关于C编译过程和库的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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