为什么在编译时需要共享库 [英] why do we need the shared library during compile time

查看:75
本文介绍了为什么在编译时需要共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在可执行文件的编译期间需要共享库?我的理由是,由于共享库未包含在我的可执行文件中,而是在运行时加载的,因此在编译期间不需要使用共享库。还是我错过了什么?

Why we need the presence of the shared library during the compile time of my executable? My reasoning is that since shared library is not included into my executable and is loaded during the runtime, it is not supposed to be needed during compile time. Or Am I missing something?

#include<stdio.h>
int addNumbers(int, int); //prototype should be enough, no? 
int main(int argc, char* argv[]){
  int sum = addNumbers(1,2);
  printf("sum is %d\n", sum);
  return 0;
}

我有 libfoo.so 在我当前的目录中,但是我将其名称更改为 libfar.so ,发现在编译时需要共享库,或者共享库没有编译。

I had the libfoo.so in my current dir but I changed its name to libfar.so to find that shared lib is needed at compile or it doesn't compile.

gcc -o main main.c -L。 -lfoo 给出 main.c :(。text + 0x28):取消引用'addNumber'

我认为仅拥有共享库的名称就足够了。共享库本身不是必需的,因为它可以在LD_LIBRARY_PATH中找到并在运行时动态加载。

I think it should be enough to only have the name of the shared library. The shared library itself is not needed since it is found in the LD_LIBRARY_PATH and loaded dynamically at runtime. Is there something else needed other than the name of the shared lib?

推荐答案

无需任何操作 >时间,因为C具有翻译单元单独编译的概念。但是,一旦所有不同的来源都被编译了,就该将所有内容链接在一起了。共享库的概念在标准中不存在,但现在已经很常见了,因此这是 common 链接程序的处理方式:

Nothing is needed at compile time, because C has a notion of separate compilation of translation units. But once all the different sources have been compiled, it is time to link everything together. The notion of shared library is not present in the standard but is it now a common thing, so here is how a common linker proceeds:


  • 它在所有编译的模块中查找已定义或仅声明了外部链接的标识符

  • 它在库(静态和动态)中查找已使用但未使用的标识符定义。然后,它链接来自静态库的模块,并存储来自动态库的引用。但是至少在类Unix上,它需要访问共享库以获取潜在的必需(声明的和未定义的)标识符,以确保它们已被定义或可以在其他链接库中找到,无论它们是静态的还是动态的

这将生成可执行文件。然后在加载时,动态加载器会知道所需的所有动态模块,并将它们与实际的可执行文件一起加载到内存中(如果它们尚不存在),并构建一个(虚拟的)内存映射

This produces the executable file. Then at load time, the dynamic loader knows all the dynamic modules that are required and loads them in memory (if they are not already there) along with the actual executable and builds a (virtual) memory map

这篇关于为什么在编译时需要共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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