链接到某事物意味着什么? [英] What does it mean to link against something?

查看:82
本文介绍了链接到某事物意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常听到链接到库"一词. 我是编译器的新手,因此是链接的手,所以我想对此有所了解.

I commonly hear the term "to link against a library". I'm new to compilers and thus linking, so I would like to understand this a bit more.

链接到库是什么意思,什么时候不这样做会引起问题?

What does it mean to link against a library and when would not doing so cause a problem?

推荐答案

库是包含已编译代码的存档".通常,您想使用现成的库来使用一些自己不想实现的功能(例如,解码JPEG,解析XML,为您提供GUI小部件,就给它命名).

A library is an "archive" that contains already compiled code. Typically, you want to use a ready-made library to use some functionality that you don't want to implement on your own (e.g. decoding JPEGs, parsing XML, providing you GUI widgets, you name it).

通常在C和C ++中使用库是这样的:您#include库的某些标头包含函数/类声明-即它们告诉编译器您需要使用的符号存在于某个地方,而没有实际提供他们的代码.无论何时使用它们,编译器都会在目标文件中放置一个占位符,该占位符表示在其余对象模块可用时,链接时将解析该函数​​调用.

Typically in C and C++ using a library goes like this: you #include some headers of the library that contain the function/class declarations - i.e. they tell the compiler that the symbols you need do exist somewhere, without actually providing their code. Whenever you use them, the compiler will place in the object file a placeholder, which says that that function call is to be resolved at link time, when the rest of the object modules will be available.

然后,在链接时,您必须指定实际的库,在该库中可以找到库功能的已编译代码.然后,链接程序将将此编译后的代码与您的代码链接,并生成最终的可执行文件(或者,对于动态库,它将为加载程序添加相关信息,以使加载程序在运行时执行动态链接).

Then, at the moment of linking, you have to specify the actual library where the compiled code for the functions of the library is to be found; the linker then will link this compiled code with yours and produce the final executable (or, in the case of dynamic libraries, it will add the relevant information for the loader to perform the dynamic linking at runtime).

如果您未指定要链接的库,则链接器将具有未解析的引用-即它将看到已声明了某些函数,您在代码中使用了它们,但找不到它们的实现;这就是臭名昭著的未定义参考错误"的原因.

If you don't specify that the library is to be linked against, the linker will have unresolved references - i.e. it will see that some functions were declared, you used them in your code, but their implementation is nowhere to be found; this is the cause of the infamous "undefined reference errors".

请注意,所有此过程与编译由多个.cpp文件组成的项目时通常发生的过程相同:每个.cpp是独立编译的(通常仅通过原型知道其他函数中定义的功能) (以.h文件编写),最后将所有内容链接在一起以生成最终的可执行文件.

Notice that all this process is identical to what normally happens when you compile a project that is made of multiple .cpp files: each .cpp is compiled independently (knowing of the functions defined in the others only via prototypes, typically written in .h files), and at the end everything is linked together to produce the final executable.

这篇关于链接到某事物意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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