[英]What does it mean to link against something?
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? 链接库是什么意思,什么时候不这样做会导致问题?
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 (eg decoding JPEGs, parsing XML, providing you GUI widgets, you name it).
通常,您希望使用现成的库来使用您不希望自己实现的某些功能(例如,解码JPEG,解析XML,为您提供GUI小部件,您可以命名)。
Typically in C and C++ using a library goes like this: you #include
some headers of the library that contain the function/class declarations - ie they tell the compiler that the symbols you need do exist somewhere, without actually providing their code. 通常在C和C ++中使用库是这样的:你
#include
包含函数/类声明的库的一些头 - 即它们告诉编译器你需要的符号确实存在于某个地方,而不是实际提供它们的代码。 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 - ie 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".
这是臭名昭着的“未定义的参考错误”的原因。
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. 请注意,所有这些过程都与编译由多个
.cpp
文件组成的项目时通常发生的过程相同:每个.cpp
都是独立编译的(只知道其他人通过原型定义的函数,通常用.h
文件编写) ),最后一切都链接在一起,以产生最终的可执行文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.