链接到某物是什么意思?

2022-01-11 00:00:00 compiler-construction linker c++

我经常听到链接到库"这个词.我是编译器和链接的新手,所以我想更多地了解这一点.

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 包含函数/类的库的一些标头 declarations - 即它们告诉编译器您需要的符号确实存在于某个地方,而没有实际提供它们的代码.每当您使用它们时,编译器都会在目标文件中放置一个占位符,表示该函数调用将在链接时解析,此时其余的目标模块将可用.

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.

相关文章