c - C 编译器如何发现 -lm 指向文件 libm.a?

标签 c linux compiler-construction programming-languages

linux下C程序中的.a文件是什么? 是库文件吗?

To merge with the math library libm.a you would type

 cc -o program_name prog.c -lm

when you compile the program. The -lm means: add in libm. If we wanted to add in the socket library libsocket.a to do some network programming as well, we would type

 cc -o program_name prog.c -lm -lsocket

and so on. 

编译器如何发现 -lm 指向文件 libm.a 和 -lsocket 指向文件 libsocket.a?

如果我们在程序中加入头文件,编译时是否一定要提到库?

最佳答案

正如 Ignacio 所说,.a 文件是静态库。 “a”代表“存档”,.a 文件由名为“ar”的程序构建。

每个 .a 文件包含一个或多个 .o 文件和名称索引。在链接过程中,只有包含已用名称的 .o 文件会包含在最终程序中。这样一来,就不会包含整个 C 库,而只会复制使用过的函数,例如“printf”。

编译器如何找到库?它有一个内置的搜索库路径集合。例如,如果被问到,GCC 会告诉您它的搜索路径:

# gcc -print-search-dirs
install: /usr/lib/gcc/i686-redhat-linux/4.4.4/
programs: =/usr/libexec/gcc/i686-redhat-linux/4.4.4/:/usr/libexec/gcc/i686-redhat-linux/4.4.4/:/usr/libexec/gcc/i686-redhat-linux/:/usr/lib/gcc/i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/:/usr/libexec/gcc/i686-redhat-linux/4.4.4/:/usr/libexec/gcc/i686-redhat-linux/:/usr/lib/gcc/i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/:/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../i686-redhat-linux/bin/i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../i686-redhat-linux/bin/
libraries: =/usr/lib/gcc/i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../i686-redhat-linux/lib/i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../i686-redhat-linux/lib/:/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../i686-redhat-linux/4.4.4/:/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../:/lib/i686-redhat-linux/4.4.4/:/lib/:/usr/lib/i686-redhat-linux/4.4.4/:/usr/lib/

您可以使用“-L/path”选项添加更多库搜索路径。

在这些路径中,它首先搜索以“.so”扩展名命名的“动态库”。然后它会搜索扩展名为“.a”的静态库。它总是在名称的前面添加“lib”。

关于c - C 编译器如何发现 -lm 指向文件 libm.a?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3907498/

相关文章:

c - 在不修改源码的情况下查找多进程程序中调用了哪些函数?

linux - 什么时候处理信号以及为什么某些信息会卡住?

c# - 为什么 C#/VS 没有像 Java/Eclipse 这样的自动构建功能?

Android NDK 中通过 SWIG 的 Java 字符串用奇怪的字符代替空字节

c - 调试器: How do I get "Mutex Owned" or "Mutex Free" info in a crash dump?

c - 为什么在引用 int 变量的大小时必须使用 %ld?

c++ - 未找到命令,C++ 应用程序

optimization - 如何为 Lua 5.1 构建反编译器?

java - JIT 编译器和执行

c - 使不选择所需的目标